jquery validate: apply custom method if conditionally required

后端 未结 1 1705
轮回少年
轮回少年 2021-01-24 14:07

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

1条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-24 14:29

    "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 empty
            return true;
        } else {  // otherwise, use your rule
            if (!/Invalid|NaN/.test(new Date(value))) {
                return new Date(value) > new Date($(params).val());
            }
            return isNaN(value) && isNaN($(params).val()) || (Number(value) > Number($(params).val()));
        }
    },'Must be greater than {0}.');
    

    0 讨论(0)
提交回复
热议问题