Conditional Validation in asp.net MVC4

ASP.NET MVC 3 uses jquery unobtrusive validation to perform client side validation. So you could either write a custom RequiredIf validation attribute or use the one provided in Mvc Foolproof Validation and then:

public class MyViewModel
{
    [RequiredIf("IsFlagSet", true)]
    [Remote("ValidateHosFin", "EditEncounter")]
    [MinLength(6)]
    public string HospitalFinNumber { get; set; }

    public bool IsFlagSet { get; set; }

    public string EncFlag { get; set; }
}

Then all that’s left is to include the jquery.validate.js and jquery.validate.unobtrusive.js scripts or use the corresponding bundle in ASP.NET MVC 4 that includes them.

Leave a Comment