我只是尝试将validate.js用于我的一个小项目,我印象最深刻的是这个插件给你的定制选项的数量,现在我真正想做的是,我有以下验证码:
$('#testimonials-form').validate({
rules: {
"t-title": {
required: true,
minlength: 5
},
"t-text": {
required: true,
minlength: 15
},
"person-name": {
required: true,
minlength: 4
},
"photo": {
required: true,
accept: 'image/*'
}
},
messages: {
"t-title": {
required: "A title is needed",
minlength: "minimum 4 characters"
},
"t-text": {
required: "A testimonial is needed",
minlength: "minimum 15 characters"
},
"person-name": {
required: "A name is needed",
minlength: "minimum 4 characters"
},
"photo" : {
required: "An image for the testimonial giver is needed",
accept: "Only image file type is accpeted , please check that the file you tried to upload was an image"
}
},
submitHandler: function(form) {
return false;
},
});
现在每次我关注一个输入字段,并且验证cretiria不符合,错误显示在输入字段的底部,我想要的是一个自定义的错误消息,所以我遇到了以下函数文档 HERE ,onfocusout
函数,现在如果我使用下面的函数:
onfocusout: function(e , b) {
var exe = e.target;
var b = null;
}
默认验证消息停止显示,但是如何在onfocusout函数中获取错误消息,以便我可以在我的自定义HTML中显示错误,I.E。以下错误消息:
messages: {
"t-title": {
required: "A title is needed",
minlength: "minimum 4 characters"
},
"t-text": {
required: "A testimonial is needed",
minlength: "minimum 15 characters"
},
"person-name": {
required: "A name is needed",
minlength: "minimum 4 characters"
},
"photo" : {
required: "An image for the testimonial giver is needed",
accept: "Only image file type is accpeted , please check that the file you tried to upload was an image"
}
},
插件传递给onfocusout
函数的两个参数是:
(在控制台中查看以上内容。)
所以我的问题是,如何获得有关输入字段模糊的错误消息?还是不可能?
答案 0 :(得分:1)
onfocusout
默认情况下已启用。但是,默认情况下验证是“懒惰的”。这意味着在第一次单击提交之后,通过字段的选项卡不会执行任何操作。请参阅第二个要点here。
在字段被标记为无效之前,验证是懒惰的:在第一次提交表单之前,用户可以通过字段标记而不会收到恼人的消息 - 在有机会实际输入之前,它们不会被窃听正确值
首先点击提交,然后查看onfocusout
功能...
默认:http://jsfiddle.net/31fjzogp/
在对象文字中指定onfocusout
选项时,您将完全覆盖默认功能。
我不确定你在这里发生了什么......
onfocusout: function(e , b) {
var exe = e.target;
var b = null;
}
根据源代码,开发人员只为此函数提供一个参数,因此b
将不会为您执行任何操作。即使b
是事件对象,将其设置为null
也不会做任何事情。基本上,您的自定义函数只是完全禁用onfocusout
。
所以我的问题是,如何获得有关输入字段模糊的错误消息?还是不可能?
将onfocusout
从“懒惰”切换为“渴望”......
onfocusout: function(element) {
this.element(element);
}
DEMO:http://jsfiddle.net/3pLr49rs/
默认验证消息停止显示,但是如何在onfocusout函数中获取错误消息,以便我可以在自定义HTML中显示错误。
当您违反默认onfocusout
功能时,它们停止显示,您不将消息放在onfocusout
功能的中。< / p>
正如您所看到的,messages
选项在您实施时效果很好:http://jsfiddle.net/3pLr49rs/1/
要自定义消息容器的展示位置或HTML,您可以使用errorPlacement
,errorElement
等选项。请参阅:http://jsfiddle.net/3pLr49rs/2/