javascript - RegEx which allows only english text and no special charactes - Stack Overflow

I want to validate a text field (first name) using javascript. such that it should only contain text. N

I want to validate a text field (first name) using javascript. such that it should only contain text. NO special characters and No numbers.and since it is just the first name it should only contain one word. (no spaces)

Allowed:

  • John
  • john

Not Allowed

  • john kennedy.
  • John kennedy.
  • john123.
  • 123john.

I tried this but its not working.

if( !validateName($fname)) 
    {
     alert("name invalid");
    }   


function validateName($name) {
var nameReg = /^A-Za-z*/;
if( !nameReg.test( $name ) ) {
    return false;
 } else {
   return true;
  }
}

EDIT: I tried

var nameReg = /^[A-Za-z]*/;

but it still doesn't show the alert box when I enter john123 or 123john.

I want to validate a text field (first name) using javascript. such that it should only contain text. NO special characters and No numbers.and since it is just the first name it should only contain one word. (no spaces)

Allowed:

  • John
  • john

Not Allowed

  • john kennedy.
  • John kennedy.
  • john123.
  • 123john.

I tried this but its not working.

if( !validateName($fname)) 
    {
     alert("name invalid");
    }   


function validateName($name) {
var nameReg = /^A-Za-z*/;
if( !nameReg.test( $name ) ) {
    return false;
 } else {
   return true;
  }
}

EDIT: I tried

var nameReg = /^[A-Za-z]*/;

but it still doesn't show the alert box when I enter john123 or 123john.

Share Improve this question edited Jan 12, 2015 at 17:13 vsync 131k59 gold badges340 silver badges423 bronze badges asked Feb 24, 2013 at 17:26 user1910290user1910290 5374 gold badges15 silver badges28 bronze badges 2
  • In your EDIT you forgot $ at the end, without it everything will pass validation. – Igor Jerosimić Commented Feb 24, 2013 at 17:40
  • Have you tried /[^A-Za-z]/g ? adding the global "g" makes it look at all the characters. – peterchon Commented Aug 13, 2013 at 23:48
Add a ment  | 

2 Answers 2

Reset to default 2

nameReg needs to be /^[a-z]+$/i (or some varient). The ^ matches the start of the string and $ matches the end. This is "one or more a-z characters from the start to the end of the string, case-insensitive." You can change + to *, but then the string could be empty.

http://jsfiddle/ExplosionPIlls/pwYV3/1/

Use a character class:

var nameReg = /^[A-Za-z]*/;

Without the containing [] (making it a character class), you're specifying a literal A-Za-z.

UPDATE:

Add a $ to the end of the Regex.

var nameReg = /^[A-Za-z]*$/;

Otherwise, john123 returns valid as the Regex is matching john and can ignore the 123 portion of the string.

Working demo: http://jsfiddle/GNVck/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745150581a4613850.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信