jquery alphanumeric validation

孤街醉人 提交于 2019-12-02 21:04:57

问题


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


回答1:


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




回答2:


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.




回答3:


Use

reg_password1.match(letters)



回答4:


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



来源:https://stackoverflow.com/questions/11532982/jquery-alphanumeric-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!