3

I am struggling writing a Regex for angular ng-pattern to validate a form input field.An example of the possible inputs are below

Valid input:

@tag1,@tag2,@tag3
@tag1, @tag2, @tag3
@tag1

Invalid Input:

@tag 1
@tag 1, @tag2, @tag  -3
@ta g1, @t ag2

Basically it should allow comma and comma whitespace, but not allow whitespace in between tags.

I have written a REGEX that matches all the invalid input, but when I use this in ng-pattern it does not do the correct validation.

Regex Built: /((^, @|@\s+)|@*[a-zA-Z0-9]* +[a-zA-Z0-9])/g Link: https://regex101.com/r/HMVdLD/1

Any help is much appreciated!

Steven.lin
  • 103
  • 1
  • 1
  • 11
  • 3
    Why use a regex that matches *invalid* input? – Wiktor Stribiżew Apr 13 '17 at 12:37
  • I tried negating the above expression. That does not seem to work either. – Steven.lin Apr 13 '17 at 12:41
  • 2
    Look, [`/^@[a-zA-Z0-9]+(?:,\s*@[a-zA-Z0-9]+)*$/`](https://regex101.com/r/REqF0G/1) should match all valid ones, and it is much easier. Put it into the `ng-pattern` attribute value (`ng-pattern="/pattern/"`). What about leading/trailing whitespace? Do you want it to be allowed in your input field? – Wiktor Stribiżew Apr 13 '17 at 12:44

1 Answers1

6

I suggest defining a pattern to match valid inputs, like

ng-pattern="/^@[a-zA-Z0-9]+(?:,\s*@[a-zA-Z0-9]+)*$/"

See the regex demo

If you want to disallow leading and trailing whitespace, add ng-trim="false".

Pattern details:

  • ^ - start of string
  • @ - a literal @ symbol
  • [a-zA-Z0-9]+ - 1+ alphanumerics
  • (?:,\s*@[a-zA-Z0-9]+)* - 0+ sequences of:
    • , - comma
    • \s* - 0+ whitespaces
    • @[a-zA-Z0-9]+ - same as above
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563