Reputation: 87
$('#reg_submit').click(function () {
var reg_password1 = $('#reg_password1').val();
letters = /([a-z])([0-9])/;
var errorMessage = '';
if ( ! reg_password1.value.match(letters) )
{
errorMessage = "Password must be alphanumeric";
$('#msg_regpass1').html(errorMessage).show();
}
else {
$('#msg_regpass1').html('').hide();
}
});
i used the above jquery code for applying alphanumeric validation to my registration page.but i am getting the javascript error related to match(), something match is undefined like that. can anyone suggest the solution for the above problem or please provide some other code for getting alphanumeric validation for above code. that letters pattern also not working properly for alphanumeric validation.can anyone suggest other pattern
thanks in advance
Upvotes: 1
Views: 23111
Reputation: 88378
As all you asked for is a suggestion, here's a start: The regex you probably want is /^[a-z\d]+$/i
. Your existing regex matches only when your regex contains a single lowercase letter or digit anywhere in the string; the suggestion says that every character must be.
Alternatively you can use a slight variation to your regex: /[^a-z\d]/i
which matches a single non-alphanumeric value. Then tweak your logic to say: if I have a match here, then the string is invalid.
As far as match
being undefined goes, read up on the regex-related methods in JavaScript. Some belong to strings, some belong to the Regexp
class.
Upvotes: 1
Reputation: 63588
your jQuery .val();
method will return you the value, thus change this line
if(!reg_password1.value.match(letters))
to
if(!reg_password1.match(letters))
I'm guessing you want a slightly different regex too.
If all characters must be a-z or 0-9 (case insensitive) then try this:
/^[a-z0-9]*$/i
However, that all said if this is truly for a password field, you should let the user choose symbols like $,#,!,@,%_,-,(,[,),] etc. to enable them to choose a strong password. ;-)
Upvotes: 0
Reputation: 4885
This one is working for me:
var reg_password1 = 'test123#';
var letters = /^[a-zA-Z0-9]+$/;
var result = letters.test(reg_password1);
console.log(result);
Upvotes: 7