user1334095
user1334095

Reputation: 87

jquery alphanumeric validation

$('#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

Answers (4)

Ray Toal
Ray Toal

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

scunliffe
scunliffe

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

silentw
silentw

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);​

DEMO

Upvotes: 7

matt3141
matt3141

Reputation: 4423

Use

reg_password1.match(letters)

Upvotes: 0

Related Questions