ASP.NET MVC DataAnnotation Required 1 from 3 property

mvc data annotations validation example
custom data annotation in mvc
data annotations c# required
mvc data annotations client side validation
email validation using data annotation in mvc
asp net validation
dataannotations maxlength
custom data annotation c#

I am creating a project using ASP.NET MVC.

My model class looks like this:

public class CaseInformation
{
    public int Id { get; set; }

    public string CaseNumber { get; set; }
    public string RitNumber { get; set; }
    public string ApilNumber { get; set; }

    public DateTime Date { get; set; }

    public double CaseInvolvedRevenue { get; set; }
    public string CaseShortDescription { get; set; }
    public string CaseUpdateStatus { get; set; }

    public CompanyDetails CompanyDetails { get; set; }
    public int CompanyDetailsId { get; set; }
}

Here CaseNumber, RitNumber, ApilNumber only 1 is required. I can not put [Required] on all of them. How do I do that? Please help.


You can implement the IValidatableObject interface in your CaseInformation class itself. Here's what it would look like:

public class CaseInformation : IValidatableObject
{
    ...

    public IEnumerable<ValidationResult> Validate(ValidationContext ctx)
    {
        if (string.IsNullOrWhiteSpace(CaseNumber) &&
            string.IsNullOrWhiteSpace(RitNumber) &&
            string.IsNullOrWhiteSpace(ApilNumber))
        {
            yield return new ValidationResult("Your error message here.");
        }
    }
}

The Validate(ValidationContext) method is called by the framework when performing model validation. Here, we're just checking if all three values are missing and if so, we signal an error by returning a ValidationResult with a custom error message.

In order to use the Data Annotations Model Binder in an ASP.NET MVC application, you first need to add a reference to the Range – Enables you to validate whether the value of a property falls The Product class in Listing 1 illustrates how to use these validator Figure 3: Missing required fields. I am building my first app with ASP.NET, and I am using Entity Framework. File Upload ASP.NET MVC 3.0. 362. DataAnnotation for Required property. 109.


One approach is, You may implement your own validation attribute like below -

public class CaseInfoRequiredAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var caseInfo = (CaseInformation) validationContext.ObjectInstance;
        if (string.IsNullOrEmpty(caseInfo.CaseNumber) &&
            string.IsNullOrEmpty(caseInfo.RitNumber) &&
            string.IsNullOrEmpty(caseInfo.ApilNumber))
        {
            return new ValidationResult("Either CaseNumber or RitNumber or ApilNumber is required.");
        }
        return ValidationResult.Success;        
    }
}

Then use the custom attribute for any one of the field

public class CaseInformation
{
    public int Id { get; set; }

    [CaseInfoRequired]
    public string CaseNumber { get; set; }
    public string RitNumber { get; set; }
    public string ApilNumber { get; set; }

    public DateTime Date { get; set; }

    public double CaseInvolvedRevenue { get; set; }
    public string CaseShortDescription { get; set; }
    public string CaseUpdateStatus { get; set; }

    public CompanyDetails CompanyDetails { get; set; }
    public int CompanyDetailsId { get; set; }
}

NET MVC Music Store sample application. 04/21/2011; 3 minutes to read We can do things like leave required fields blank or type letters in the Price us to describe the rules we want applied to our model properties, and ASP.NET on Model Validation using Data Annotation attributes, see the MSDN  Next click the Browse tab and browse to the location where you downloaded (and unzipped) the Data Annotations Model Binder sample (see Figure 1 ). Figure 1: Adding a reference to the Data Annotations Model Binder ( Click to view full-size image) Select both the Microsoft.Web.Mvc.DataAnnotations.dll assembly and the System.ComponentModel.DataAnnotations.dll assembly and click the OK button.


You could add an IsValid() function to your model that returns true/false and append errors to the ModelState.

CaseInformation:

public class CaseInformation
{
    public int Id { get; set; }

    public string CaseNumber { get; set; }
    public string RitNumber { get; set; }
    public string ApilNumber { get; set; }

    public DateTime Date { get; set; }

    public double CaseInvolvedRevenue { get; set; }
    public string CaseShortDescription { get; set; }
    public string CaseUpdateStatus { get; set; }

    public CompanyDetails CompanyDetails { get; set; }
    public int CompanyDetailsId { get; set; }

    public bool IsValid(out IDictionary<string, string> errors)
    {
        errors = new Dictionary<string, string>();
        if (string.IsNullOrWhiteSpace(CaseNumber) && string.IsNullOrWhiteSpace(RitNumber) &&
            string.IsNullOrWhiteSpace(ApilNumber))
        {
            errors.Add("MyError", "At least one Case, Rit or Apil number is required.");
        }
        return errors.Count == 0;
    }
}

And then in your controller:

public ActionResult Index(CaseInformation model)
{
    if (!model.IsValid(out var errors))
    {
        foreach (KeyValuePair<string, string> error in errors)
        {
            ModelState.AddModelError(error.Key, error.Value);
        }                
    }
    if (ModelState.IsValid)
    {
        // it worked
    }
    else
    {
        // must be errors
    }
    return View();
}

And then in your view:

@Html.ValidationSummary(false, "Please fix the below and try again.")

73, 74 DbContext, 77 StoreManagerController and views, 78–79 Artist property​, NET Dynamic Data DataAnnotations classes, 348 NuGet Gallery, 426–430 NET MVC 1, 4 ASP. NET MVC 3 AsyncController, 419–421 overview, 5–9 ASP 308–309 software requirements, 17–18 Web API compared to, 280–281 ASP. Let us understand some of the validator attributes that we can use in MVC. Types of Data Annotations in ASP.NET MVC Required This attribute specifies that the value is mandatory and cannot be skipped. Syntax [Required(ErrorMessage="Please enter name"),MaxLength(30)] DataType This attribute is used to specify the datatype of the model. Syntax


1. When match is found, corresponding incoming data will be assigned to the parameter. 2. 3. In case assignment is not possible because of data type mismatch exception will be thrown. Step 1 – Decorate Properties with DataAnnotation attributes In ASP.NET MVC we will use DataAnnotation attributes for validation. In this chapter, I explained how to use Data Annotation for validating input field in ASP.NET MVC 5. I also explained how to add custom validation rule in DataAnnotation. In the next chapter, you will learn Remote Validation in ASP.NET MVC. Remote Validation checks user input field instantly when the focus jumps out from input control.


With ASP.NET Core, SignalR, Docker, and Azure Rami Vemula. Custom. Validations. using. DataAnnotation 1. Required: Makes a property required. 2. StringLength: Validates that a string property has at most the given 3. Range: Validates the property value falls within the given range. 4. Mvc.ModelBinding. The StringLength attribute lets you set the maximum length of a string property, and optionally its minimum length. Value types (such as decimal, int, float, DateTime) are inherently required and don't need the [Required] attribute. Having validation rules automatically enforced by ASP.NET Core helps make your app more robust.


NET Web API runs the validation rules you set against the properties of your model NET framework, you can use data annotation attributes to declaratively specify 1. Create a new ASP.NET MVC 4 project named RequestValidation, using the Create a new empty API controller named EmployeesController. 3. Create a  Part 6: Using Data Annotations for Model Validation. 04/21/2011; 3 minutes to read +2; In this article. by Jon Galloway. The MVC Music Store is a tutorial application that introduces and explains step-by-step how to use ASP.NET MVC and Visual Studio for web development.