我正在研究我认为棘手的 jquery 验证情况。
我遇到一种情况,仅当一个字段为空时,我才需要抛出错误。
<div class='row'>
<div class='col-sm-3'>
<div class='form-group'>
<label for="arrivalDate">Assignment Start</label>
<input type="text" class="form-control" id="arrivalDate" placeholder="mm/dd/yyyy" value="" name="arrivalDate" />
</div>
</div>
<div class='col-sm-3'>
<div class='form-group'>
<label for="assignmentEnd">Assignment End</label>
<input type="text" class="form-control" id="assignmentEnd" placeholder="mm/dd/yyyy" value="" name="assignmentEnd" />
</div>
</div>
所以,我希望发生的是:
如果分配结束字段中有文本,则到达日期字段不能为空。它应该抛出一条错误消息。
我尝试编写一个验证器,但我认为我做得不对:
$.validator.addMethod("contractCheck", function(value,element,params) {
if ((value).val().length != 0) {
return true;
}
return false;
},
"Field can't be blank"
);
代码中调用:
assignmentEnd: {
contractCheck: "#arrivalDate"
},
assignmentEnd: {
required: "This can not be blank."
},
*注意我没有这样的,我只是想包括我如何调用它。它是像其他字段一样被调用和评估的正确格式。
当我尝试运行此代码时,它实际上会抛出错误,但会提交表单(这不应该发生),因此我无法查找错误消息。
最佳答案
I have a situation in which I need will need an error thrown only if one field is blank.
除了使用依赖函数在第二个字段上声明required
规则之外,您不需要编写自定义规则或执行任何其他操作。
$('#yourform').validate({
rules: {
assignmentEnd: {
required: function(element) {
// required ONLY when other field is NOT blank
return $('#arrivalDate').is(':filled');
}
}
}
});
关于javascript - 仅当一个字段为空时 Jquery 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40981636/