-1

I need to validate building name in the below format (length is 1-50)

my regex for alphanumeric and specified characters check

     /^[a-zA-Z0-9\s\)\(\]\[\._-&]+$/

Its showing invalid expression but when i exclude & it works fine.

     /^[a-zA-Z0-9\s\)\(\]\[\._-]+$/   

Actual Format

  1. Building name should use Letters, Numbers, Underscore_, Hyphen-, Period., Square-brackets[], Parentheses() ,Ampersand &
  2. It should not start and end with any special characters continuously

Valid:

  1. Empire3 State&Building[A]
  2. 7Empire.State-Building(A)
  3. Empire(State)_Building[A]12

Invalid:

  1. @#$@$@building))
  2. ().-building2
  3. $buildingseven[0]&.

i am struggling for 2nd format. how to check for continuous allowed special characters at first and last. Any help is very much appreciated.

Shalini
  • 219
  • 1
  • 5
  • 16

1 Answers1

2

Escape the - character:

/^(?!\W.+\W$)[a-zA-Z0-9\s\)\(\]\[\._\-&]+$/

In a character class, the - character signifies a range of characters (e.g 1-9). Because the ASCII code for & is less than _, your regular expressions fails to parse correctly.

Also, to check that no special characters are at the beginning or end, use \W (a character other than a letter, digit or underscore) in a lookahead to check that both the start and the end are not "special characters". If you count an underscore as a special character, use [^A-Za-z0-9] instead of \W.

var validBuildingName = /^(?!\W.+\W$)[a-zA-Z0-9\s\)\(\]\[\._\-&]+$/;
validBuildingName.test('(example)'); // false
validBuildingName.test('(example'); // true
validBuildingName.test('example)'); // true
validBuildingName.test('example'); // true
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83