Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript regex : only english letters allowed

Quick question: I need to allow an input to only accept letters, from a to z and from A to Z, but can't find any expression for that. I want to use the javascript test() method.

like image 281
yoda Avatar asked Jun 18 '10 21:06

yoda


People also ask

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.


2 Answers

let res = /^[a-zA-Z]+$/.test('sfjd'); console.log(res);

Note: If you have any punctuation marks or anything, those are all invalid too. Dashes and underscores are invalid. \w covers a-zA-Z and some other word characters. It all depends on what you need specifically.

like image 83
meder omuraliev Avatar answered Sep 20 '22 10:09

meder omuraliev


Another option is to use the case-insensitive flag i, then there's no need for the extra character range A-Z.

var reg = /^[a-z]+$/i; console.log( reg.test("somethingELSE") ); //true console.log( "somethingELSE".match(reg)[0] ); //"somethingELSE" 

Here's a DEMO on how this regex works with test() and match().

like image 30
Shawn Moore Avatar answered Sep 22 '22 10:09

Shawn Moore