Skip to content

Instantly share code, notes, and snippets.

@davidisnotnull
Created February 2, 2022 22:21

Revisions

  1. David Johnson created this gist Feb 2, 2022.
    18 changes: 18 additions & 0 deletions checkbox-validation.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    window.onload = () => {
    /*
    Custom jquery-validation handling for check boxes must equal true
    Decorate C# model bool properties with
    [Range(typeof(bool), 'true', 'true', ErrorMessage = 'Add your error message')]
    to make their corresponding checkbox validate to 'must equal true'
    */
    var defaultRangeValidator = $.validator.methods.range;
    $.validator.methods.range = function (value, element, param) {
    if (element.type === 'checkbox') {
    // if it's a checkbox return true if it is checked
    return element.checked;
    } else {
    // otherwise run the default validation function
    return defaultRangeValidator.call(this, value, element, param);
    }
    }
    };