views:

55

answers:

1

What will be the regular expression in javascript to match a name field, which allows only letters, apostrophes and hyphons?

so that jhon's avat-ar or Josh is valid?

Thanks

+2  A: 

Yes.

^[a-zA-Z'-]+$

Here,

  • ^ means start of the string, and $ means end of the string.
  • […] is a character class which anything inside it will be matched.
  • x+ means the pattern before it can be repeated once or more.

Inside the character class,

  • a-z and A-Z are the lower and upper case alphabets,
  • ' is the apostrophe, and
  • - is the hyphen. The hyphen must appear at the beginning or the end to avoid confusion with the range separator as in a-z.

Note that this class won't match international characters e.g. ä. You have to include them separately e.g.

^[-'a-zA-ZÀ-ÖØ-öø-ſ]+$
KennyTM
@Robert - no. Both beginning and end are OK for "-"
DVK
I think this works for me, but it would be great if you could give me a little info on how you constructed this... I understood the most part of it except that how the hyphon position (at start and at the end) in your regular expression would work (as DVK mentioned in the above comment) and the significance of + sign... Just for my understanding! thank you!
zoom_pat277
@KennyTM: That is indeed helpful... Thank you so much! I should start working more on Regular expression...Thanks
zoom_pat277