skip to Main Content

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.

2

Answers


  1. 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}$

    Login or Signup to reply.
  2. Your issue is more of a typo, but if you look closely at the second character class in your regex:

    [a-z -.]{0,25}
    

    You will see that you have -. as a range, which will be interpreted as all characters from space to dot, going by the ASCII table. This includes * and ", which is why you are currently getting a match. If you move the dash to the end of the character class, it will work:

    [a-z .-]{0,25}
    

    Your updated script:

    let g_Check = /^[a-z]+[a-z .-]{0,25}$/i;
    let bl = g_Check.test("abc*"de");
    console.log(bl);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search