3

I have created a regular expression for Name validation where only “_”, “-“, “‘“, “. “ allowed.

Here is regular expression:

^[a-zA-Z][a-zA-Z0-9\.\-_']{1,24}$

Problem is this its allowing name having @, Check Fiddle demo:

var str = "deepak@";
var str2 = "@@";
alert(str.match("^[a-zA-Z][a-zA-Z0-9\.\-_]{1,24}$"));//allowing why?
alert(str2.match("^[a-zA-Z][a-zA-Z0-9\.\-_]{1,24}$"));//not allowing

Expected: Name having @ should not allow.

Note: When i tested this regex in https://regex101.com/#javascript its working good

0

2 Answers 2

4

Don't forget to use regex delimiter in Javascript:

alert(str.match(/^[a-zA-Z][a-zA-Z0-9\.\-_]{1,24}$/));

Or even better:

alert(str.match(/^[a-zA-Z][\w'.-]{1,24}$/));

Updated JSFiddle

Sign up to request clarification or add additional context in comments.

Comments

-1

I guess this would do the same:

str.match(/^\w{1,24}$/);

Definition:

The \w metacharacter is used to find a word character. A word character is a character from a-z, A-Z, 0-9, including the _ (underscore) character.

1 Comment

You allow digits at the beginning of the string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.