jquery 验证:如果有条件需要,应用自定义方法
jquery validate: apply custom method if conditionally required
我的表单中有三个字段:状态、询问日期和预计日期
如果我的 Status=A,我希望在验证中需要我的预计日期
此外,我希望验证的预期日期始终大于询问日期
这是我的规则
rules: {
status: {
required: true,
},
ask_date: {
required: true,
date:true,
},
expected_date: {
required: function(element){
if($('#status').val()=='A'){
return true;
} else {
return false;
}
},
greaterThan: "#ask_date",
date:true,
},
如何说只有字段满足要求才调用greaterThan方法?
"greaterThan" 是自定义的 jquery 验证方法,我在此处使用来自单独堆栈溢出的验证方法 Validate that end date is greater than start date with jQuery
jQuery.validator.addMethod("greaterThan",
function(value, element, params) {
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}.');
"How can I say invoke the greaterThan
method ONLY when the field meets the required
conditions?"
由于该字段在这些条件下只有 required
,理想情况下,当该字段留空时,应触发其他规则的 none。但是,您的自定义方法中缺少一个部分,可以在字段留空时忽略它。
针对条件 this.optional(element)
进行测试将确保您的自定义规则不会在空白字段上强制执行。
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}.');
我的表单中有三个字段:状态、询问日期和预计日期
如果我的 Status=A,我希望在验证中需要我的预计日期 此外,我希望验证的预期日期始终大于询问日期
这是我的规则
rules: {
status: {
required: true,
},
ask_date: {
required: true,
date:true,
},
expected_date: {
required: function(element){
if($('#status').val()=='A'){
return true;
} else {
return false;
}
},
greaterThan: "#ask_date",
date:true,
},
如何说只有字段满足要求才调用greaterThan方法?
"greaterThan" 是自定义的 jquery 验证方法,我在此处使用来自单独堆栈溢出的验证方法 Validate that end date is greater than start date with jQuery
jQuery.validator.addMethod("greaterThan",
function(value, element, params) {
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}.');
"How can I say invoke the
greaterThan
method ONLY when the field meets therequired
conditions?"
由于该字段在这些条件下只有 required
,理想情况下,当该字段留空时,应触发其他规则的 none。但是,您的自定义方法中缺少一个部分,可以在字段留空时忽略它。
针对条件 this.optional(element)
进行测试将确保您的自定义规则不会在空白字段上强制执行。
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}.');