MVC3 Unobtrusive validation for checkbox

When using unobtrusive validation for checkboxes, it does not validate an unchecked checkbox which is marked as required. Its a known issue. By default, all the checkbox required conditions are ignored in unobtrusive validation.

A workaround for this issue is to add a custom attribute and some code change in the unobtrusive JavaScript library.

1. Create a custom attribute

   

    public class RequireCheckedAtrribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            return value != null && value is bool && (bool)value;
        }
        public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            ModelClientValidationRule rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationType = "requirechecked";
            yield return rule;
        }
    }
  
 

2. replace the condition at line 294 in jquery.validate.unobtrusive.js (not minified) with the below lines


var s = $(options.element).attr('data-val-requirechecked');
if (s != null && s != 'undefined')
    options.message = s;
if (options.element.tagName.toUpperCase() !== "INPUT" || !($(options.element).is(':checkbox') &&
(s == null || s == 'undefined'))) {

 

The new code from line 292 looks as below


adapters.add("required", function (options) {
        // jQuery Validate equates "required" with "mandatory" for checkbox elements
        var s = $(options.element).attr('data-val-requirechecked');
        if (s != null && s != 'undefined')
            options.message = s;
        if (options.element.tagName.toUpperCase() !== "INPUT" || !($(options.element).is(':checkbox') &&
(s == null || s == 'undefined'))) {

            setValidationValues(options, "required", true);
        }
    });
 

3. In the model, mark your checkbox field with RequireCheckedAtrribute attribute.

Example:

 
[RequireCheckedAtrribute]
public bool AcceptTerms {get; set;}

 

You can download updated script file from here

 

Happy codingSmile

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.