Client-side checkbox validation not working in MVC3

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?

you’re missing the js for client-side validation. mvc3 needs a custom validator function that matches ur “required-checkbox” type. add this to ur page:

jQuery.validator.addMethod("required-checkbox", function(value, element) {
    return element.checked;
});

without the js side, mvc can’t validate checkboxes on the client.

You need both the JavaScript validator method and an adapter to make client-side validation work. Adding the jQuery validator isn’t enough; you’ve got to register an adapter that connects your validation type to the method. Add this code with your validator:

jQuery.validator.unobtrusive.adapters.add("required-checkbox", function(options) {
    options.rules["required-checkbox"] = true;
    options.messages["required-checkbox"] = options.message;
});

This adapter shows the unobtrusive validation system how to handle your custom “required-checkbox” type. Without it, there’s no way to connect your server-side attribute to the client-side method, which is why you’re only getting server-side validation right now.

interesting issue! first, check if your jquery validation scripts are actually loading on the page - custom validators won’t fire without the core libs. are you using unobtrusive validation? you might need to call $.validator.unobtrusive.parse() after adding your custom method.