jQuery 验证:如何为正则表达式验证添加规则?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/280759/
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 validate: How to add a rule for regular expression validation?
提问by PeterFromCologne
I am using the jQueryvalidation plugin. Great stuff! I want to migrate my existing ASP.NET solution to use jQuery instead of the ASP.NET validators. I am missing a replacement for the regular expressionvalidator. I want to be able to do something like this:
我正在使用jQuery验证插件。好东西!我想迁移我现有的 ASP.NET 解决方案以使用 jQuery 而不是 ASP.NET 验证器。我缺少正则表达式验证器的替代品。我希望能够做这样的事情:
$("Textbox").rules("add", { regularExpression: "^[a-zA-Z'.\s]{1,40}$" })
How do I add a custom ruleto achieve this?
如何添加自定义规则来实现这一点?
回答by PeterFromCologne
Thanks to the answer of redsquare I added a method like this:
感谢 redsquare 的回答,我添加了一个这样的方法:
$.validator.addMethod(
"regex",
function(value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Please check your input."
);
now all you need to do to validate against any regex is this:
现在您需要做的就是针对任何正则表达式进行验证:
$("#Textbox").rules("add", { regex: "^[a-zA-Z'.\s]{1,40}$" })
Additionally, it looks like there is a file called additional-methods.js that contains the method "pattern", which can be a RegExp when created using the method without quotes.
此外,看起来有一个名为 additional-methods.js 的文件,其中包含方法“模式”,当使用不带引号的方法创建时,它可以是一个 RegExp。
Edit
编辑
The pattern
function is now the preferred way to do this, making the example:
该pattern
函数现在是执行此操作的首选方法,示例如下:
$("#Textbox").rules("add", { pattern: "^[a-zA-Z'.\s]{1,40}$" })
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/additional-methods.js
http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/additional-methods.js
回答by redsquare
You can use the addMethod()
您可以使用 addMethod()
e.g
例如
$.validator.addMethod('postalCode', function (value) {
return /^((\d{5}-\d{4})|(\d{5})|([A-Z]\d[A-Z]\s\d[A-Z]\d))$/.test(value);
}, 'Please enter a valid US or Canadian postal code.');
good article here https://web.archive.org/web/20130609222116/http://www.randallmorey.com/blog/2008/mar/16/extending-jquery-form-validation-plugin/
回答by bshack
I had some trouble putting together all the pieces for doing a jQuery regular expression validator, but I got it to work... Here is a complete working example. It uses the 'Validation' plugin which can be found in jQuery Validation Plugin
我在将所有部分放在一起做一个 jQuery 正则表达式验证器时遇到了一些麻烦,但我让它工作了......这是一个完整的工作示例。它使用可在jQuery Validation Plugin 中找到的“Validation”插件
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="http://YOURJQUERYPATH/js/jquery.js" type="text/javascript"></script>
<script src="http://YOURJQUERYPATH/js/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
$().ready(function() {
$.validator.addMethod("EMAIL", function(value, element) {
return this.optional(element) || /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(value);
}, "Email Address is invalid: Please enter a valid email address.");
$.validator.addMethod("PASSWORD",function(value,element){
return this.optional(element) || /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}$/i.test(value);
},"Passwords are 8-16 characters with uppercase letters, lowercase letters and at least one number.");
$.validator.addMethod("SUBMIT",function(value,element){
return this.optional(element) || /[^ ]/i.test(value);
},"You did not click the submit button.");
// Validate signup form on keyup and submit
$("#LOGIN").validate({
rules: {
EMAIL: "required EMAIL",
PASSWORD: "required PASSWORD",
SUBMIT: "required SUBMIT",
},
});
});
</script>
</head>
<body>
<div id="LOGIN_FORM" class="form">
<form id="LOGIN" name="LOGIN" method="post" action="/index/secure/authentication?action=login">
<h1>Log In</h1>
<div id="LOGIN_EMAIL">
<label for="EMAIL">Email Address</label>
<input id="EMAIL" name="EMAIL" type="text" value="" tabindex="1" />
</div>
<div id="LOGIN_PASSWORD">
<label for="PASSWORD">Password</label>
<input id="PASSWORD" name="PASSWORD" type="password" value="" tabindex="2" />
</div>
<div id="LOGIN_SUBMIT">
<input id="SUBMIT" name="SUBMIT" type="submit" value="Submit" tabindex="3" />
</div>
</form>
</div>
</body>
</html>
回答by Sam
No reason to define the regex as a string.
没有理由将正则表达式定义为字符串。
$.validator.addMethod(
"regex",
function(value, element, regexp) {
var check = false;
return this.optional(element) || regexp.test(value);
},
"Please check your input."
);
and
和
telephone: { required: true, regex : /^[\d\s]+$/, minlength: 5 },
tis better this way, no?
这样更好,不是吗?
回答by Markus Jarderot
Extending PeterTheNiceGuy's answer a bit:
稍微扩展 PeterTheNiceGuy 的回答:
$.validator.addMethod(
"regex",
function(value, element, regexp) {
if (regexp.constructor != RegExp)
regexp = new RegExp(regexp);
else if (regexp.global)
regexp.lastIndex = 0;
return this.optional(element) || regexp.test(value);
},
"Please check your input."
);
This would allow you to pass a regex object to the rule.
这将允许您将正则表达式对象传递给规则。
$("Textbox").rules("add", { regex: /^[a-zA-Z'.\s]{1,40}$/ });
Resetting the lastIndex
property is necessary when the g
-flag is set on the RegExp
object. Otherwise it would start validating from the position of the last match with that regex, even if the subject string is different.
lastIndex
当对象g
上设置了-flag时,需要重置属性RegExp
。否则,即使主题字符串不同,它也会从与该正则表达式的最后一个匹配的位置开始验证。
Some other ideas I had was be to enable you use arrays of regex's, and another rule for the negation of regex's:
我的其他一些想法是让您能够使用正则表达式数组,以及另一个否定正则表达式的规则:
$("password").rules("add", {
regex: [
/^[a-zA-Z'.\s]{8,40}$/,
/^.*[a-z].*$/,
/^.*[A-Z].*$/,
/^.*[0-9].*$/
],
'!regex': /password|123/
});
But implementing those would maybe be too much.
但是实施这些可能太多了。
回答by J?rn Zaefferer
As mentioned on the addMethod documentation:
正如addMethod 文档中提到的:
Please note: While the temptation is great to add a regex method that checks it's parameter against the value, it is much cleaner to encapsulate those regular expressions inside their own method. If you need lots of slightly different expressions, try to extract a common parameter. A library of regular expressions: http://regexlib.com/DisplayPatterns.aspx
请注意:虽然添加一个正则表达式方法来检查它的参数与值的关系是很诱人的,但将这些正则表达式封装在它们自己的方法中要干净得多。如果您需要许多略有不同的表达式,请尝试提取一个公共参数。正则表达式库:http: //regexlib.com/DisplayPatterns.aspx
So yes, you have to add a method for each regular expression. The overhead is minimal, while it allows you to give the regex a name (not to be underestimated), a default message (handy) and the ability to reuse it a various places, without duplicating the regex itself over and over.
所以是的,您必须为每个正则表达式添加一个方法。开销很小,同时它允许您为正则表达式命名(不要低估)、默认消息(方便)以及在不同地方重用它的能力,而无需一遍又一遍地复制正则表达式本身。
回答by Kris Nobels
I got it to work like this:
我让它像这样工作:
$.validator.addMethod(
"regex",
function(value, element, regexp) {
return this.optional(element) || regexp.test(value);
},
"Please check your input."
);
$(function () {
$('#uiEmailAdress').focus();
$('#NewsletterForm').validate({
rules: {
uiEmailAdress:{
required: true,
email: true,
minlength: 5
},
uiConfirmEmailAdress:{
required: true,
email: true,
equalTo: '#uiEmailAdress'
},
DDLanguage:{
required: true
},
Testveld:{
required: true,
regex: /^[0-9]{3}$/
}
},
messages: {
uiEmailAdress:{
required: 'Verplicht veld',
email: 'Ongeldig emailadres',
minlength: 'Minimum 5 charaters vereist'
},
uiConfirmEmailAdress:{
required: 'Verplicht veld',
email: 'Ongeldig emailadres',
equalTo: 'Veld is niet gelijk aan E-mailadres'
},
DDLanguage:{
required: 'Verplicht veld'
},
Testveld:{
required: 'Verplicht veld',
regex: '_REGEX'
}
}
});
});
Make sure that the regex is between /
:-)
确保正则表达式介于/
:-)
回答by Wiktor Stribi?ew
You may use pattern
defined in the additional-methods.js
file. Note that this additional-methods.js file must be included afterjQuery Validate dependency, then you can just use
您可以使用文件中pattern
定义的additional-methods.js
。注意这个 additional-methods.js 文件必须包含在jQuery Validate 依赖之后,然后你就可以使用
$("#frm").validate({
rules: {
Textbox: {
pattern: /^[a-zA-Z'.\s]{1,40}$/
},
},
messages: {
Textbox: {
pattern: 'The Textbox string format is invalid'
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>
<form id="frm" method="get" action="">
<fieldset>
<p>
<label for="fullname">Textbox</label>
<input id="Textbox" name="Textbox" type="text">
</p>
</fieldset>
</form>
回答by ArunDhwaj IIITH
This is working code.
这是工作代码。
function validateSignup()
{
$.validator.addMethod(
"regex",
function(value, element, regexp)
{
if (regexp.constructor != RegExp)
regexp = new RegExp(regexp);
else if (regexp.global)
regexp.lastIndex = 0;
return this.optional(element) || regexp.test(value);
},
"Please check your input."
);
$('#signupForm').validate(
{
onkeyup : false,
errorClass: "req_mess",
ignore: ":hidden",
validClass: "signup_valid_class",
errorClass: "signup_error_class",
rules:
{
email:
{
required: true,
email: true,
regex: /^[A-Za-z0-9_]+\@[A-Za-z0-9_]+\.[A-Za-z0-9_]+/,
},
userId:
{
required: true,
minlength: 6,
maxlength: 15,
regex: /^[A-Za-z0-9_]{6,15}$/,
},
phoneNum:
{
required: true,
regex: /^[+-]{1}[0-9]{1,3}\-[0-9]{10}$/,
},
},
messages:
{
email:
{
required: 'You must enter a email',
regex: 'Please enter a valid email without spacial chars, ie, [email protected]'
},
userId:
{
required: 'Alphanumeric, _, min:6, max:15',
regex: "Please enter any alphaNumeric char of length between 6-15, ie, sbp_arun_2016"
},
phoneNum:
{
required: "Please enter your phone number",
regex: "e.g. +91-1234567890"
},
},
submitHandler: function (form)
{
return true;
}
});
}
回答by staabm
we mainly use the markup notation of jquery validation plugin and the posted samples did not work for us, when flags are present in the regex, e.g.
我们主要使用 jquery 验证插件的标记符号,当正则表达式中存在标志时,发布的示例对我们不起作用,例如
<input type="text" name="myfield" regex="/^[0-9]{3}$/i" />
therefore we use the following snippet
因此我们使用以下代码段
$.validator.addMethod(
"regex",
function(value, element, regstring) {
// fast exit on empty optional
if (this.optional(element)) {
return true;
}
var regParts = regstring.match(/^\/(.*?)\/([gim]*)$/);
if (regParts) {
// the parsed pattern had delimiters and modifiers. handle them.
var regexp = new RegExp(regParts[1], regParts[2]);
} else {
// we got pattern string without delimiters
var regexp = new RegExp(regstring);
}
return regexp.test(value);
},
"Please check your input."
);
Of course now one could combine this code, with one of the above to also allow passing RegExp objects into the plugin, but since we didn't needed it we left this exercise for the reader ;-).
当然,现在可以将此代码与上述代码之一结合起来,以允许将 RegExp 对象传递到插件中,但由于我们不需要它,因此我们将这个练习留给读者;-)。
PS: there is also bundled plugin for that, https://github.com/jzaefferer/jquery-validation/blob/master/src/additional/pattern.js
PS:还有捆绑插件,https://github.com/jzaefferer/jquery-validation/blob/master/src/additional/pattern.js