我使用 jQuery 验证插件,我的表单可以按如下方式验证(假设我有 2 个字段 A 和 B):
有效:
我点击 A 并输入一些内容,然后删除。然后我点击了B。在这种情况下,会显示验证消息。
它不起作用:
我**单击了 A,但没有输入任何内容。然后我单击了 B。在这种情况下,不会显示与字段 A 相关的相关验证消息。但我希望它如上所示。
我尝试在 validate 方法中使用 onsubmit、onkeyup 和 onclick 参数,但没有任何意义。我怎样才能提供这个?
Razor :
jQuery(function () {
$.validator.setDefaults(
$("#myform").validate({
//onsubmit: false, ???
//onkeyup: true, ???
//onclick:true, ???
onkeyup: function(element){this.element(element);},
rules: {
'Applicant.Name': "required",
'Applicant.Surname': "required"
},
messages: {
'Applicant.Name': "Please enter your Name",
'Applicant.Surname': "Please enter your Surname"
}
})
);
});
最佳答案
您的代码:
jQuery(function () {
$.validator.setDefaults(
$("#myform").validate({ .... })
);
});
重要提示:您不能将 .validate()
.setDefaults()
中的方法.这没有任何意义。
.validate()
方法用于在表单上初始化插件(带选项)。.validator.setDefaults()
方法用于设置将应用于页面上所有表单的选项,但是,此方法不会初始化任何内容。
如果您想设置 #myform
的选项,仅使用 .validate()
...
jQuery(function () {
$("#myform").validate({
// options only for #myform
});
});
如果您想设置用于页面上所有表单的选项,请使用 .validator.setDefaults()
。然后使用.validate()
在每种表格上...
jQuery(function () {
$.validator.setDefaults({
// options for all forms on page
});
$("#myform").validate({
// options only for #myform
});
$("#myform2").validate({
// options only for #myform2
});
});
<小时/>
默认插件操作:
默认情况下,插件不会执行任何“key-up”验证,直到该字段最初由另一个事件验证。
所以这是默认 onkeyup
的经过适当修改的版本回调函数,因此它将提供立即 onkeyup
验证。
onkeyup: function (element, event) {
if (event.which === 9 && this.elementValue(element) === "") {
return;
} else {
this.element(element);
}
}
<小时/>
您的代码:
//onsubmit: false, ???
//onkeyup: true, ???
//onclick:true, ???
这些选项绝不能设置为true
.
文档:
<小时/>onfocusout
Type: Boolean or Function()
Validate elements (except checkboxes/radio buttons) on blur. If nothing is entered, all rules are skipped, except when the field was already marked as invalid. Set to a Function to decide for yourself when to run validation. A boolean true is not a valid value.
<小时/>onkeyup
Type: Boolean or Function()
Validate elements on keyup. As long as the field is not marked as invalid, nothing happens. Otherwise, all rules are checked on each key up event. Set to false to disable. Set to a Function to decide for yourself when to run validation. A boolean true is not a valid value.
<小时/>onclick
Type: Boolean or Function()
Validate checkboxes and radio buttons on click. As long as the field is not marked as invalid, nothing happens. Otherwise, all rules are checked on each key up event. Set to false to disable. Set to a Function to decide for yourself when to run validation. A boolean true is not a valid value.
onsubmit
Type: Boolean or Function()
Validate the form on submit. As long as the field is not marked as invalid, nothing happens. Otherwise, all rules are checked on each key up event. Set to false to disable. Set to a Function to decide for yourself when to run validation. A boolean true is not a valid value.
关于javascript - jQuery 验证插件无法在 Keyup 上进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20530018/