VendettaTurkey VendettaTurkey - 1 month ago 9
AngularJS Question

Regex Javascript, negative lookahead with white space

In my Javascript angular application I have a regex to validate usernames.

The issue I am facing, after doing much research is that utilising negative lookahead with expressions that contain white spaces is not working.

The Requirements



Username can be composed of many alphanumeric strings split at most with one space. Spaces at edges are not allowed. also the username should be filtered against a couple of banned names.

1)



(/^[a-zA-Z\d]+([\s][a-zA-Z\d]+)+?$/).test("admin may not be used")


allows alphanumeric words to be split by one consequent space at a time, and disallows spaces at edges

2)



(/^(?!(?:admin|alfred)$)[a-zA-Z\d]+$/).test("admin")


works and word admin is not allowed

3) merging both:



(/^(?!(?:admin|alfred)$)[a-zA-Z\d]+([\s][a-zA-Z\d]+)+?$/).test("admin may not be used")


fails! and will allow the banned word admin to be used.

Expected Result:



Both filters are expected to work, that is the banned words list , as well as consequent space filter.
Can you please point what possibly is wrong with my expression?

Answer Source

You may consider using

/^(?!.*\b(?:admin|alfred)\b)[a-zA-Z\d]+(?:\s[a-zA-Z\d]+)+$/

or a bit longer one that is a bit more effecient (but less readable):

/^(?!(?:admin|alfred)\b)[a-zA-Z\d]+(?:\s(?!(?:admin|alfred)\b)[a-zA-Z\d]+)+$/

See the regex demo

If one word usernames are allowed, replace the last + (1 or more repetitions) with a ? (1 or 0 repetitions) quantifier (demo).

If you use it in AngularJS, also use ng-trim="false" to make sure leading and trailing whitespaces are not allowed.

Pattern details:

  • ^ - start of string
  • (?!.*\b(?:admin|alfred)\b) - after zero or more chars (.*) there can't be admin or alfred as whole words (else, the regex will return false)
  • [a-zA-Z\d]+ - 1 or more alphanumerics
  • (?: - start of a non-capturing group
    • \s - a whitespace
    • [a-zA-Z\d]+ - 1 or more alphanumerics
  • )+ - end of the non-capturing group that will be repeated 1 or more times
  • $ - end of string.