简体   繁体   中英

jquery validation. custom rules using selector syntax

I'm writing a system utilizing jQuery Validation that pulls in custom rules, messages via jSON and dynamically validates multiple forms in single pages. All is going swimmingly except I cannot find any decent information on the correct syntax for custom rules....

For example:

I know this works....

"ui_txt_GCPostcode": {
    "required": "input[name=ui_rb_ItemAddress][value=Recipient]:checked"
}

I'm saying here that ui_txt_GCPostcode is required only when a radio button from a list with the name ui_rb_ItemAddress and the value Recipient is checked.

This to me looks like I am able to assign ruled based upon dependency expressions containing specific selector attributes.

This however doesn't work.....

"ui_sel_PCSelect": {
        "required": "input[name=ui_txt_PostCodeSearch]:hidden, input[name=ui_txt_Address]:hidden"
    }

The validator is firing even though I have ui_txt_Address visible.

I'm even setting up the validator with the ignore hidden property eg.

                // Validate the form once the defaults are set.
                $validator = $form.validate({
                    // This prevents validation from running on every
                    // form submission by default.
                    onsubmit: false,
                    messages: messages,
                    rules: rules,
                    errorContainer: $container,
                    errorLabelContainer: $("ol", $container),
                    wrapper: "li",

                    // Ignore hidden items. Why is this not working??
                    ignore: ":hidden"
                });

Any ideas?? I'm on a pretty tight deadline and I'm starting to panic.

This selector:

"input[name=ui_txt_PostCodeSearch]:hidden, input[name=ui_txt_Address]:hidden"

Will trigger the required rule if either the first or second part are true (see the multiple selector ). This is why the rule fires even if one is visible.

If you want to make the element required if both are hidden, you may have to supply a dependency-function instead of an expression:

"ui_txt_GCPostcode": {
    "required": function() {
        return $("input[name='ui_rb_ItemAddress'][value='Recipient']:checked").length &&
            $("input[name='ui_rb_ItemAddress'][value='Recipient']:checked").length;
    }
}

As for the ignore property not working, that's for ignoring fields matching the selector (so :hidden will tell validator not to validate hidden fields). Not sure if you were using it this way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM