blueren blueren - 1 year ago 50
Javascript Question

Regular Expression advice for [Alphanumeric][alphanumeric.-_@] 31 characters

I'm looking to do a name check using regex in javascript.

  1. The value can contain alphanumeric and following special characters
    ('-', '.' '_' and '@').

  2. It should always start with an alphanumeric character.

  3. It should not be an empty string.

  4. Maximum allowed length for this parameter is 31 characters.

  5. This parameter is case-insensitive.

I came up with this, but feel it's incorrect. Any advice on how to have it foolproof?



You are quite close, here is the corrected regex:


I applied the folloing changes:

  • Added $ anchor to the end
  • used the i-modifier for case-insensitivity
  • replaced a-zA-Z0-9_ with \w and moved - to the end of the character class
  • changed fixed repetition {30} to {0,30}

See the Regex101-Demo with some unit tests.