Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, how do I check if string is only letters+numbers (underscore allowed)?

How do I check that?

I want to allow all A-Za-z0-9 , and underscore. Any other symbol, the function should return false.

like image 211
TIMEX Avatar asked Nov 24 '11 06:11

TIMEX


Video Answer


2 Answers

You can use a regular expression:

function isValid(str) { return /^\w+$/.test(str); }

\w is a character class that represents exactly what you want: [A-Za-z0-9_]. If you want the empty string to return true, change the + to a *.

To help you remember it, the \w is a word character. (It turns out that words have underscores in JavaScript land.)

like image 190
Tikhon Jelvis Avatar answered Oct 03 '22 23:10

Tikhon Jelvis


I think this is a solution:

function check(input) {
  return /^\w+$/i.test(input);
}
like image 36
ioseb Avatar answered Oct 03 '22 22:10

ioseb