问题描述
我正在使用 jQuery验证插件,并希望在插件检测到有效或无效时运行自己的代码输入.
I'm using the jQuery Validation Plugin and want to run my own code when the plugin detects a valid or invalid input.
我发现我需要的两个.validate()
选项是success
和showErrors
,我可以让它们两个都独立工作:
I've figured out that the two .validate()
options I need are success
and showErrors
and I can get them both to work on their own:
var validator = $('#form').validate({
rules: {
name: "required",
email: {
required: true,
email: true
}
},
success: function() {
console.log('success');
}
在进行有效输入时记录success
.并且showErrors
也可以正常工作:
That logs success
any time a valid input is made. And showErrors
works correctly also:
var validator = $('#form').validate({
rules: {
name: "required",
email: {
required: true,
email: true
}
},
showErrors: function() {
console.log('error');
}
但是当我尝试将两者结合时,无论输入是否有效,每次都会记录error
:
But when I try to combine the two, error
is logged every time regardless of whether the input is valid:
var validator = $('#form').validate({
rules: {
name: "required",
email: {
required: true,
email: true
}
},
success: function() {
console.log('success');
},
showErrors: function() {
console.log('error');
}
选项的顺序没有任何作用.
The order of the options doesn't have any effect.
有人知道为什么这两个选项不能同时使用,以及如何在有效和无效输入上运行自己的函数吗?
Does anyone know why the two options don't work together and how I can run my own functions on valid and invalid inputs?
推荐答案
"showErrors"不仅仅在检测到错误时被调用,每次您更改输入时都会被调用,而不管您键入的值是什么.
"showErrors" is not called just when an error is detected, it's called everytime you change the input, regardless the value you typed.
"showErrors"接收两个参数:"errorMap"和"errorList".要验证是否确实存在错误,您必须检查以下值之一:
"showErrors" receives two parameters: "errorMap" and "errorList". To verify if there really was an error you have to check one of those values:
showErrors: function(errorMap, errorList) {
if (errorsList.length > 0) {
console.log('error');
}
}
您还可以处理showErrors函数中的成功"事件,因为它是在当前验证程序上下文中调用的.
You can also handle the "success" event inside the showErrors function, since it's called in the current validator context.
showErrors: function(errorMap, errorList) {
if (errorsList.length == 0) {
this.currentElements.addClass("success");
}
}
这篇关于jQuery表单验证-成功+ showErrors的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!