asp.net-mvcasp.net-mvc-3entity-frameworkentity-framework-4asp.net-mvc-4

One of two properties is required from the data model


Let's say I have a Person class with FirstName and LastName. I want that the user must enter at least one of the two values in the UI but he may not have to enter each of them.

If I place the Required attribute / data annotation on each of them, that makes both of them required.

How do I make a server side validation (with client side validation, too) for this rule?


Solution

  • You could use a custom attribute for this. In short, the custom attribute will retrieve both values and then ensure at least one has a value. See this page for more information. Here is an example (untested code):

    [AttributeUsage(AttributeTargets.Property, AllowMultiple =false, Inherited = false)]
      public class ValidatePersonName: ValidationAttribute
      {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
          string FirstName = (string)validationContext.ObjectType.GetProperty("FirstName").GetValue(validationContext.ObjectInstance, null);
    
          string LastName = (string)validationContext.ObjectType.GetProperty("LastName").GetValue(validationContext.ObjectInstance, null);
    
      //check at least one has a value
      if (string.IsNullOrEmpty(FirstName) && string.IsNullOrEmpty(LastName))
            return new ValidationResult("At least one is required!!");
    
          return ValidationResult.Success;
        }
      }
    

    Usage:

    class Person{
    
     [ValidatePersonName]
     FirstName{get;set;}
    
     LastName{get;set;}
    }