开发者

Regex jquery the proper way

I am trying to do a few form validation checks and I am facing some problems. First of all could some one tell me is the match function the right way to check a string. Secondly could some one explain why is this not working and what is the right format. I am trying to check if there is any开发者_JAVA百科thing except alphabets (Letters) It works fine for numbers and returns an error but if i type (.) / ; etc anything except a number it allows and no error is reported.

  if ($("#firstname").val().match(/[a-zA-Z]/))

I want to only allow alphabets nothing else. One more thing this confuses me alot if there is a match the error will go in else right? For instance.

   if ($("#firstname").val().match(/[a-zA-Z]/))
   {  // no match carry on... }else

   {/ found match display error }

Thanks help is much appreciated!


You're probably looking for /^[a-zA-Z]+$/.

At present you're merely searching for an alphabetic character in the string, not searching for a string that is comprised only of them.

As for your second question, of course match succeeds if a match was found, so your conditional handling is backwards.

if ($("#firstname").val().match(/^[a-zA-Z]+$/)) {
   // string contains only alphabetcharacters
}
else {
   // non-alphabet characters found, or string was empty
}


This code should work:

if ($("#firstname").val().match(/^([a-zA-Z])*$/))


About match(), look at this answer to other question:
JS/Jquery, Match not finding the PNG = match('/gif|jpg|jpeg|png/')

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜