最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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/

发布评论

评论列表(0)

  1. 暂无评论