[英]RegEx in jQuery Validator addMethod
I need a few RegEx for my jQuery validator custom methods. 我的jQuery验证程序自定义方法需要一些RegEx。 The first which I thought was going to be easy was just limiting a username to only US letters, numbers, and no special characters.
我认为第一个简单的方法是将用户名限制为仅美国字母,数字和没有特殊字符。 I came up with
^[a-zA-Z0-9]+$
but it doesn't seem to work. 我想出了
^[a-zA-Z0-9]+$
但似乎不起作用。 Maybe it is due to the way it appears in the function: 也许是由于它在函数中的出现方式:
$.validator.addMethod(
"legalName",
function(value, element) {
return (element.value != "^[a-zA-Z0-9]+$");
},
"Use a valid username."
);
The second is validating the password which is essentially the same limitations with the addition of a required number of certain characters such as an uppercase, number, ect. 第二个是验证密码,本质上是相同的限制,只是增加了一定数量的某些字符,例如大写,数字等。 I figure once I get the username RegEx down the password wont be too hard, just a matter of fitting in
{1}
's and such within the expression. 我认为一旦我获得了RegEx用户名,密码就不会太难,只需要适合表达式中的
{1}
。
The last part of my question is how do I add a second method ("legalPassword") inside of the original .addMethod
or do I need a create a whole other $.validator.addMethod
? 我的问题的最后一部分是如何在原始
.addMethod
内添加第二个方法(“ legalPassword”),还是需要创建一个完整的其他$.validator.addMethod
?
$(document).ready(function() {
$("#form1").validate({
rules: {
username: {
legalName: true,
required: true,
maxlength: 35
}
},
});
});
and the table code: 和表代码:
<form id="form1" method="post" action="">
<div class="form-row"><span class="label">Username *</span><input type="text" name="username" /></div>
<div class="form-row"><input class="submit" type="submit" value="Submit"></div>
</form>
New code (still not working): 新代码(仍然无法正常工作):
$.validator.addMethod(
"legalName",
function(value, element) {
/^[a-zA-Z0-9]+$/.test( value );
},
"Use a valid username."
);
return this.optional(element) || /^[a-zA-Z0-9]+$/.test( value );
Try using the Regex.test function instead to do the check against your string. 尝试使用Regex.test函数代替对您的字符串进行检查。
/^[a-zA-Z0-9]+$/.test( element.value );
See here for more info: http://www.javascriptkit.com/javatutors/redev3.shtml 有关更多信息,请参见此处: http : //www.javascriptkit.com/javatutors/redev3.shtml
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.