Ali
Ali

Reputation: 267049

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.

Upvotes: 16

Views: 59754

Answers (4)

Vlad
Vlad

Reputation: 9481

Here you go:

function isLetter(s)
{
  return s.match("^[a-zA-Z\(\)]+$");    
}

Upvotes: 6

Edgar Hernandez
Edgar Hernandez

Reputation: 4030

You could use Regular Expressions...

functions isLetter(str) { return str.match("^[a-zA-Z()]+$"); }

Oops... my bad... this is wrong... it should be

functions isLetter(str) {
    return "^[a-zA-Z()]+$".test(str);
}

As the other answer says... sorry

Upvotes: 1

Kris
Kris

Reputation: 41827

If memory serves this should work in javascript:

function containsOnlyLettersOrParenthesis(str)
(
    return str.match(/^([a-z\(\)]+)$/i);
)

Upvotes: 2

gnarf
gnarf

Reputation: 106332

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

Upvotes: 46

Related Questions