I’m working on a custom validation attribute for making checkbox fields mandatory in my MVC3 application. Here’s what I’ve built so far:
public class MandatoryCheckbox : ValidationAttribute, IClientValidatable
{
public MandatoryCheckbox()
: base("This field is required") { }
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 = "checkboxrequired";
yield return validationRule;
}
}
The problem I’m facing is that this validation only works on the server side when my controller action runs and checks ModelState.IsValid
. I need it to work on the client side before the form gets submitted to the server.
Right now users have to submit the form and wait for a page refresh to see the validation error. I want the validation message to appear immediately when they try to submit without checking the required checkbox.
What changes do I need to make to get this working on the client side? Do I need to add some JavaScript or modify the validation rule setup?