Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating alphabetic only string in javascript

How can I quickly validate if a string is alphabetic only, e.g

var str = "!";
alert(isLetter(str)); // false

var str = "a";
alert(isLetter(str)); // true

Edit : I would like to add parenthesis i.e () to an exception, so

var str = "(";

or

var str = ")";

should also return true.

like image 753
Ali Avatar asked Mar 15 '10 21:03

Ali


People also ask

How do you validate only letters in JavaScript?

Use the test() method to check if a string contains only letters, e.g. /^[a-zA-Z]+$/. test(str) . The test method will return true if the string contains only letters and false otherwise.

How do I restrict only alphaNumeric in JavaScript?

You will use the given regular expression to validate user input to allow only alphanumeric characters. Alphanumeric characters are all the alphabets and numbers, i.e., letters A–Z, a–z, and digits 0–9.

How do I check if a string contains letters?

To check if a string contains any letters, use the test() method with the following regular expression /[a-zA-Z]/ . The test method will return true if the string contains at least one letter and false otherwise.


1 Answers

Regular expression to require at least one letter, or paren, and only allow letters and paren:

function isAlphaOrParen(str) {
  return /^[a-zA-Z()]+$/.test(str);
}

Modify the regexp as needed:

  • /^[a-zA-Z()]*$/ - also returns true for an empty string
  • /^[a-zA-Z()]$/ - only returns true for single characters.
  • /^[a-zA-Z() ]+$/ - also allows spaces
like image 165
gnarf Avatar answered Sep 18 '22 18:09

gnarf