I’m working on a custom validation attribute for mandatory checkbox fields in my MVC3 application. I built this validation class:
public class MandatoryCheckbox : ValidationAttribute, IClientValidatable
{
public MandatoryCheckbox()
: base("must be checked") { }
public override bool IsValid(object inputValue)
{
return (bool)inputValue == true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metaData, ControllerContext controllerContext)
{
ModelClientValidationRule validationRule = new ModelClientValidationRule();
validationRule.ErrorMessage = FormatErrorMessage(metaData.GetDisplayName());
validationRule.ValidationType = "required-checkbox";
yield return validationRule;
}
}
The problem is that validation only happens on the server side when my controller action runs and checks ModelState.IsValid
. I want the validation to happen in the browser before the form gets submitted to the server.
Right now users have to submit the form and wait for the page to reload to see the validation error. This creates a poor user experience.
What do I need to change to make this validation work on the client side instead of only server side?