banjo
banjo

Reputation: 373

Test for letters only in javascript validation

Although I have my php validation doing this, thought I may as well pop it in to javascript validation too, just to pick it up before I force a page reload.

I want to test if an input has only letters in it. I have had a look around and cant get a concise block of code to use. Any help would be great.

var x = $('firstName').val();
var onlyLetters = /^[a-zA-Z]*$/.test(myString);
if (x != onlyLetters) { display error; } return true;

I'm still new to javascript which is why I cant see why the above code isn't working. :)

Thanks in advance.

Upvotes: 0

Views: 3144

Answers (1)

Marc B
Marc B

Reputation: 360662

.test() returns a boolean true/false result. You then compare this true/false to the original string you tested, which will fail. It should be

if (!onlyletters) { display error; }

since it's already a boolean value.

Upvotes: 5

Related Questions