ng-pattern to allow alpha and certain special characters

12,893

Solution 1

Let's see:

  • Should allow only Alpha characters => [a-zA-Z]
  • Allow space => [ ] or \s
  • Allow certain special characters - _ \ / - . ’ ' => [_\\\/.’'-]

So, combining all that, the pattern will look like:

ng-pattern="/^[a-zA-Z _\\\/.’'-]+$/"

This matches 1 or more (+) chars from the allowed set.

To disallow leading/trailing whitespace, use

ng-pattern="/^[a-zA-Z_\\\/.’'-]+(?: +[A-Za-z_\\\/.’'-]+)*$/" ng-trim="false"

See the regex demo

The ng-trim="false" will prevent from trimming the input sent to the regex engine. The new regex will match:

  • ^ - start of string
  • [a-zA-Z_\\\/.’'-]+ - 1 or more letters or allowed symbols other than space
  • (?: +[A-Za-z_\\\/.’'-]+)* - zero or more sequences of:
    • + - (or, \s+) - 1 or more spaces (whitespaces)
    • [A-Za-z_\\\/.’'-]+ - see above
  • $ - end of string.

Solution 2

/^([a-z _\/.'-])+$/i would do. If you want any space character instead of just space, use /(^[a-z_\/.'-]|\s)+$/i.

Share:
12,893
monda
Author by

monda

Updated on June 17, 2022

Comments

  • monda
    monda almost 2 years

    In form - name field I want to do a validation against

    • Should allow only Alpha characters
    • Allow space
    • Allow certain special characters - _ \ / - . ’

    I tried,

     ng-pattern="/^[a-z]+[_+\+/+-+.+’][a-z]*$/"
    

    Looks like I have missed out something as its not working!

  • monda
    monda over 7 years
    It failed for name - Dinesh D'Soza
  • Wiktor Stribiżew
    Wiktor Stribiżew over 7 years
    Then just add the single quote to the character class. Just keep in mind that the hyphen must be at the end, right before ].
  • Wiktor Stribiżew
    Wiktor Stribiżew over 7 years
    Your regex will match more than you think. See Why is this regex allowing a caret?
  • monda
    monda over 7 years
    Can we restrict leading/trailing whitespace ?
  • Wiktor Stribiżew
    Wiktor Stribiżew over 7 years
    So, the requirement changed ? :) Yes, it is easy.