Client-side validation for mandatory checkbox in ASP.NET MVC3

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?

Your validation attribute looks right, but you’re missing the JavaScript registration. You need to create a custom validator method after including the jQuery validation scripts. Make sure the validation method name matches your ValidationType exactly.

Here’s what you need:

$.validator.addMethod('checkboxrequired', function(value, element) {
    return $(element).is(':checked');
});

$.validator.unobtrusive.adapters.add('checkboxrequired', function(options) {
    options.rules['checkboxrequired'] = true;
    options.messages['checkboxrequired'] = options.message;
});

Put this script after your jQuery validation libraries but before any forms render. The validation will kick in right when users try to submit without checking the required checkbox.

hey! have you check if your client-side validation method is registered in JS? your c# code is solid, but it needs the jquery validator method to work on the client side. also, make sure you’ve included jquery.validate.unobtrusive.js and added your custom validation script!

you’re missing the javascript part. add a custom adapter for jquery validation like this: $.validator.addMethod('checkboxrequired', function(value, element) { return element.checked; }); then register it with $.validator.unobtrusive.adapters.add('checkboxrequired', function(options) { options.rules['checkboxrequired'] = true; });