Skip to content Skip to sidebar Skip to footer

Jquery Validate: Apply Custom Method If Conditionally Required

I have three fields in my form: status, ask date, and expected date If my Status=A, I would like my expected date to be required in validation additionally I would like my expected

Solution 1:

"How can I say invoke the greaterThan method ONLY when the field meets the required conditions?"

Since the field is only required under those conditions, ideally, none of your other rules should be fired when the field is left blank. However, there is a piece missing from your custom method that would allow it to be ignored whenever the field is left blank.

Testing against the condition, this.optional(element), will ensure that your custom rule is not enforced on a blank field.

jQuery.validator.addMethod("greaterThan", function(value, element, params) {
    if (this.optional(element)) {  // "required" not in force and field is emptyreturntrue;
    } else {  // otherwise, use your ruleif (!/Invalid|NaN/.test(newDate(value))) {
            returnnewDate(value) > newDate($(params).val());
        }
        returnisNaN(value) && isNaN($(params).val()) || (Number(value) > Number($(params).val()));
    }
},'Must be greater than {0}.');

Post a Comment for "Jquery Validate: Apply Custom Method If Conditionally Required"