Search code examples
javascriptregex

Javascript Regular Expression Not Failing When I Think It Should


My code:

let g_Check = /^[a-z]+[a-z -.]{0,25}$/i;
let bl = g_Check.test("abc*\"de"); // returns true, when I think it should return false because of the '*' and '\"'

As you can see it returns true, when I think it should return false because of the '*' and the '"'.

Other cases where it returns true when it should return false:

g_Check.test("abc&de")
g_Check.test("abc+de")
g_Check.test("abc%de")
g_Check.test("abc$de")

I want the test to only work (return true) for:

a) 25 length or less strings

b) must start with upper or lower case letter

c) the rest must only contain letters (upper or lower), spaces, minus signs and dots/periods

I would also like the expression to contain any number 0,1,2...,9.

I think that would be:

let g_Check = /^[a-z]+[a-z -.][0-9]{0,25}$/i;

But I have no way of checking this as my original expression does not work anyway.


Solution

  • Lets break it down.

    ^ Start of string, thats good

    [a-z]+ At least one in the group a-z, made case insensitive by the i option later, here is the first part of the problem.

    [a-z -.]{0,25} Here you want 0 to 25 chars, in the range a-z AND the range -., which is actually a range and not three different chars. You need to escape the - here.

    $ end of string as expected

    So the escaping is the first problem, that is easily fixed. Then what you need it so limit the first group to one char, then have the second group be at most 24.

    It would look like this: ^[a-z]{1}[a-z \-.]{0,24}$. To also allow numbers after the initial char you can just add that as a range as well: ^[a-z]{1}[a-z \-.0-9]{0,24}$