RegEx in jQuery Validator addMethod
I need a few RegEx for my jQuery validator custom methods. 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. 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 add开发者_运维问答ition 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.
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
?
$(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.
/^[a-zA-Z0-9]+$/.test( element.value );
See here for more info: http://www.javascriptkit.com/javatutors/redev3.shtml
Try Regex Mask Plugin
Browse the following link
regexMask()
精彩评论