php jQuery 验证器:验证 AlphaNumeric + Space 和 Dash
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11326910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Validator : Validate AlphaNumeric + Space and Dash
提问by Saint Robson
I have jQuery validation plugins (http://docs.jquery.com/Plugins/Validation) installed on my website.
我的网站上安装了 jQuery 验证插件 (http://docs.jquery.com/Plugins/Validation)。
I'm using this code to validate alpha-numeric from text field, and it works. but it doesn't allow space and dash (-).
我正在使用此代码来验证文本字段中的字母数字,并且它有效。但它不允许空格和破折号 (-)。
$.validator.addMethod("titleAlphaNum", function(value, element, param)
{
return value.match(new RegExp("^" + param + "$"));
});
how to make it works with space and dash? thanks.
如何使它与空格和破折号一起使用?谢谢。
回答by Tats_innit
working demohttp://jsfiddle.net/cAADx/
工作演示http://jsfiddle.net/cAADx/
/^[a-z0-9\-\s]+$/ishould do the trick!
/^[a-z0-9\-\s]+$/i应该做的伎俩!
g = /g modifier makes sure that all occurrences of "replacement"
g = /g 修饰符确保所有出现的“替换”
i = /i makes the regex match case insensitive.
i = /i 使正则表达式匹配不区分大小写。
good read:http://www.regular-expressions.info/javascript.html
好读:http : //www.regular-expressions.info/javascript.html
Hope this helps,
希望这可以帮助,
code
代码
$(function() {
$.validator.addMethod("loginRegex", function(value, element) {
return this.optional(element) || /^[a-z0-9\-\s]+$/i.test(value);
}, "Username must contain only letters, numbers, or dashes.");
$("#myForm").validate({
rules: {
"login": {
required: true,
loginRegex: true,
}
},
messages: {
"login": {
required: "You must enter a login name",
loginRegex: "Login format not valid"
}
}
});
});?
Will remove this image in 2 minssee here robert like this http://jsfiddle.net/5ykup/
将在 2 分钟内删除此图像,请在此处查看 robert 像这样http://jsfiddle.net/5ykup/


回答by Vladimir Kadalashvili
I think it will work if you pass the following RegExp as param:
我认为如果您将以下 RegExp 传递为param:
[A-za-z0-9_\-\s]+

