Search code examples
asp.net-mvcasp.net-mvc-3validation

asp.net mvc validation on 2 fields - one must exist if other entered


I have 2 text fields, text1 and text2, in my view model. I need to validate if text1 is entered then text2 must be entered and vice versa. How can this be achieved in the custom validation in the view model?

thanks.


Solution

  • You can use implement IValidatableObject (from System.ComponentModel.DataAnnotations namespace) for the server side validation on your View Model:

    public class AClass : IValidatableObject 
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string SecondName { get; set; }
            public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
            {
                if( (!string.IsNullOrEmpty(Name) && string.IsNullOrEmpty(SecondName)) || (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(SecondName)) )
                    yield return new ValidationResult("Name and Second Name should be either filled, or null",new[] {"Name","SecondName"});
            }
        }
    

    Now it make sure if both Name and SecondName are set, or null, then model is valid, otherwise, it's not.