使用正则表达式的 jQuery 验证器和可选字段
我有一个可选字段(例如“text1”),它可能是空白或仅是字母数字:
jQuery.validator.addMethod("onlyAlphaNumeric",
function(value, element) {
var regExp = new RegExp(/^[a-zA-Z0-9]+$/);
return ((this.optional(element)) || regExp.test(value));
}
, "Only aplaha-numeric characters allowed");
$("#student-search-form").validate({
rules : {
text1 : {
optional : true,
onlyAlphaNumeric: "Only a-n allowed"
}
},
messages: {
text : {
acceptOnly: " Only alpha-numeric characters allowed"
}
}
});
问题是没有进行验证,因此如果用户在“text1”中输入“!&^%(*”,则表单将变为已提交,没有错误检查
有人可以告诉我我做错了什么吗? 谢谢。
I have an optional field (say "text1") which may either be blank or only alpha-numeric:
jQuery.validator.addMethod("onlyAlphaNumeric",
function(value, element) {
var regExp = new RegExp(/^[a-zA-Z0-9]+$/);
return ((this.optional(element)) || regExp.test(value));
}
, "Only aplaha-numeric characters allowed");
$("#student-search-form").validate({
rules : {
text1 : {
optional : true,
onlyAlphaNumeric: "Only a-n allowed"
}
},
messages: {
text : {
acceptOnly: " Only alpha-numeric characters allowed"
}
}
});
The problem is no validation happens, so if user enters "!&^%(*" in 'text1', the form gets submitted, no error checks.
Can somebody please tell me what am I doing wrong?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是错误的...
对于
onlyAlphaNumeric:
,您只能输入true
或false
。我不太确定
optional:
但我知道required:
是有效的...所以将required:
设置为false.或者,您可能可以完全忽略它,因为验证器默认将字段设置为“可选”(
required:false
),除非您另外指定。看到这个类似的答案...
使用 jquery 验证插件,如何在文本框上添加正则表达式验证?
This is wrong...
For
onlyAlphaNumeric:
, you can only puttrue
orfalse
.I am not too sure about
optional:
but I knowrequired:
is valid... so setrequired:
tofalse
. Alternatively, you could probably leave it out entirely since the validator defaults to fields as being "optional" (required:false
) unless you specify otherwise.See this similar answer...
using the jquery validation plugin, how can I add a regex validation on a textbox?
您可以向验证方法添加可选 -
http://ajax。 microsoft.com/ajax/jquery.validate/1.7/additional-methods.js
验证 -
you can add optional to the validation method -
http://ajax.microsoft.com/ajax/jquery.validate/1.7/additional-methods.js
Validate -
我认为你的代码一定是这样的:
I think that your code must be something like this :