MVC Adding methods into jquery.validate.unobtrusive.js
Asked Answered
J

3

13

I recently had a question on getting checkbox validation working on the client side within a MVC project. This question was successfully answered, but raised another query.

In order for my checkbox validation to work I needed to add the following bits of javascript directly into jquery.validate.unobtrusive.js:

$jQval.addMethod("mustbetrue", function (value, element, param) {
    // check if dependency is met
    if (!this.depend(param, element))
        return "dependency-mismatch";
    return element.checked;
});

adapters.add("mustbetrue", function (options) {
    setValidationValues(options, "mustbetrue", true);
});

this worked great, but I'm unhappy about having to change this file just in case Microsoft or the validation plugin boys update the file in the future. If I'm not still working on the project this file may be overwritten without people realising it's been customised.

So with that in mind I tried adding this into an external javascript file:

$.validator.addMethod("mustbetrue", function (value, element, param) {
    // check if dependency is met
    if (!this.depend(param, element))
        return "dependency-mismatch";
    return element.checked;
});

$.validator.unobtrusive.adapters.add("mustbetrue", function (options) {
    setValidationValues(options, "mustbetrue", true);
});

Unfortunately now the client side script on my checkboxes doesn't run. Can anyone see what I'm doing wrong?

Thanks in advance

S

Jewish answered 4/8, 2011 at 13:16 Comment(0)
D
11

Sniffer,

The more I look at this, the more I shake my head (at myself).

Upon further review, Darin's method will work, provided that you add one line to his page script:

<script type="text/javascript">
    $.validator.unobtrusive.adapters.addBool("mustbetrue", "required");
    $.validator.unobtrusive.parse();
</script>

Whenever you make a change (such as adding a new adapter), you must re-parse the unobtrusive validation attributes. Since the last action in jquery.validate.unobtrusive.js is the parsing of the attributes, and the adapter is being added after the parsing, re-parsing solves this issue.

counsellorben

P.S. This solves your issue, but still leaves unresolved the issue of how to add other custom validators which do not use built-in methods from jquery.validate.js without modifying jquery.validate.unobtrusive.js.

P.P.S. I found the answer for adding custom validation methods. In order to add custom validation mmethods without modifying jquery.validate.unobtrusive.js, you need to "borrow" some of its code to add to your page script. Adding a custom method then looks like the following:

<script type="text/javascript">
    var $jQval = $.validator,
        adapters,
        data_validation = "unobtrusiveValidation";

    function setValidationValues(options, ruleName, value) {
        options.rules[ruleName] = value;
        if (options.message) {
            options.messages[ruleName] = options.message;
        }
    }

    $jQval.addMethod("mustbetrue", function (value, element, param) {
        // check if dependency is met
        if (!this.depend(param, element))
            return "dependency-mismatch";
        return element.checked;
    });

    $.validator.unobtrusive.adapters.add("mustbetrue", function (options) {
        setValidationValues(options, "mustbetrue", true);
    });

    $jQval.unobtrusive.parse();
</script>
Debroahdebs answered 4/8, 2011 at 14:0 Comment(3)
Thanks for this again! Its' weird though - although I understand exactly what you are saying and it understand it should work, as soon as I take 'addMethod' and 'add' out of jquery.validate.unobtrusive.js and put any of the above combinations into another js file it stops working! I've even put consol.log in ath addBool method within the jquery.validate.unobtrusive.js file to check that "mustbetrue" is registering and it is! As I said Weird!Jewish
I think it is pretty vital to say that you need this in your markup for the solution above to work: <input mustbetrue="true" type="textbox" />Langford
You can simplify adding your unobtrusive adapter: $.validator.unobtrusive.adapters.addBool("mustbetrue"); You also shouldn't need to call parse as long as you are adding the new validation method and adapter outside a document ready.Sanson
S
3

Unobtrusive validation is giving me nothing but grief.

In a very very simple test page, this works:

$(document).ready(function () {
    jQuery.validator.unobtrusive.adapters.add(
        'mustbetrue', ['properties'], function (options) {
            options.rules['mustbetrue'] = options.params;
            options.messages['mustbetrue'] = options.message;
        }
        );

    jQuery.validator.addMethod('mustbetrue', function (value, element, params) {
        // check if dependency is met
        if (!this.depend(param, element)) {
            return "dependency-mismatch";
        }

        switch (element.type) {
            case "checkbox":
                return element.checked;
                break;
            case "hidden":
                return (value == 'true' || value == 'True');
                break;
            default:
                alert('type = ' + element.type);
                return true;
                break;
        }
    });
});

However, when I move this code to my more complex form, suddenly it stops working and I have no idea why and no time to delve into the unobtrusive code to try and find out.

counsellorben's solution works in my more complex form.

If anyone can point me to a site that explains in detail how to properly add a custom validator to unobtrusive validation, I will be forever greatful. Each site I visit has a different solution.

Sinh answered 26/6, 2013 at 13:34 Comment(2)
This code should NOT be in a document ready function. Unobtrusive validation runs on document ready, and all the added rules are expected to be added by then.Sanson
@ErikW yeah, I was struggling with this for about an hour, and now I can confirm this code should NOT be in document ready function - it just won't work.Dav
M
1

I have no problem adding this code to an external javascript file, which i pilfered from This site

// Custom validator for checkboxs
jQuery.validator.unobtrusive.adapters.add("brequired", function (options) {    
    //bool-required for checkboxes    
    if (options.element.tagName.toUpperCase() == "INPUT" && 
        options.element.type.toUpperCase() == "CHECKBOX") 
    {
        options.rules["required"] = true;        
        if (options.message) {
            options.messages["required"] = options.message;
        }
    }
});

Are you certain that you put your script AFTER the jquery scripts in your page? Mine is the last in the list.

Metaphysics answered 27/8, 2011 at 23:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.