用户删除原始字段值时如何触发验证?
How to trigger validation when user removes original field value?
我很清楚 JQuery 验证的惰性行为。实际上,它只是半惰性的,因为如果一个字段包含有效值,失去焦点,然后更改为无效值,则立即显示错误消息,甚至在该字段再次取消焦点之前。这种行为是非常可靠的,除了在一个非常具体的场景中,我想找到一种解决方法。
如果一个字段最初包含一个有效值,将其更改为非空的无效值会触发立即验证,如预期的那样。但是 删除 初始值不会触发验证。示例:
<form id="muh-form" action="post">
<input name="input1" type="number" value="10" required min="10"/>
<br/>
<input name="input2" type="text"/>
<br/>
<input type="submit" value="Submit"/>
</form>
如果用户将“10”更改为“1”并取消对该字段的关注,则如预期的那样立即出现一条错误消息。此外,如果用户随后将“1”更改为空,则会按预期触发 required
验证。只有从初始有效到空的直接转换无法触发验证。
作为解决方法,我可以强制验证器在加载表单时立即验证所有字段吗?
您可以在change
事件中调用.valid()
。
$(document).ready(function() {
$("#muh-form").on('change', function(e) {
$("#muh-form").valid();
});
$("#muh-form").validate({
submitHandler: function (form) { }
});
});
Quote OP: If the user changes input1
to some value < 10 and unfocuses the field, validation is triggered as expected. But if the user simply removes the initial value (without first changing it) and unfocuses the field, validation is not triggered.
您描述的是插件的默认验证,称为 "lazy" 验证。 See the docs:
"Before a field is marked as invalid, the validation is lazy: Before submitting the form for the first time, the user can tab through fields without getting annoying messages – they won't get bugged before having the chance to actually enter a correct value"
如果您想改用 "eager" 验证,则需要使用自定义 onfocusout
回调函数...
onfocusout: function(element) {
// "eager" validation
this.element(element);
}
我很清楚 JQuery 验证的惰性行为。实际上,它只是半惰性的,因为如果一个字段包含有效值,失去焦点,然后更改为无效值,则立即显示错误消息,甚至在该字段再次取消焦点之前。这种行为是非常可靠的,除了在一个非常具体的场景中,我想找到一种解决方法。
如果一个字段最初包含一个有效值,将其更改为非空的无效值会触发立即验证,如预期的那样。但是 删除 初始值不会触发验证。示例:
<form id="muh-form" action="post">
<input name="input1" type="number" value="10" required min="10"/>
<br/>
<input name="input2" type="text"/>
<br/>
<input type="submit" value="Submit"/>
</form>
如果用户将“10”更改为“1”并取消对该字段的关注,则如预期的那样立即出现一条错误消息。此外,如果用户随后将“1”更改为空,则会按预期触发 required
验证。只有从初始有效到空的直接转换无法触发验证。
作为解决方法,我可以强制验证器在加载表单时立即验证所有字段吗?
您可以在change
事件中调用.valid()
。
$(document).ready(function() {
$("#muh-form").on('change', function(e) {
$("#muh-form").valid();
});
$("#muh-form").validate({
submitHandler: function (form) { }
});
});
Quote OP: If the user changes
input1
to some value < 10 and unfocuses the field, validation is triggered as expected. But if the user simply removes the initial value (without first changing it) and unfocuses the field, validation is not triggered.
您描述的是插件的默认验证,称为 "lazy" 验证。 See the docs:
"Before a field is marked as invalid, the validation is lazy: Before submitting the form for the first time, the user can tab through fields without getting annoying messages – they won't get bugged before having the chance to actually enter a correct value"
如果您想改用 "eager" 验证,则需要使用自定义 onfocusout
回调函数...
onfocusout: function(element) {
// "eager" validation
this.element(element);
}