angularjsregexng-pattern

Valid regex expressions won't work with AngularJS


I'd like to check if user input is correct for phone numbers in two formats:

I wrote a regex for this [0-9]{2} [0-9]{3} [0-9]{3} [0-9]{3}|[0-9]{2} [0-9]{7}|. It works when checked with online regex checkers, but it won't work (user can write whatever they want) when used with AngularJS: ng-pattern="[0-9]{2} [0-9]{3} [0-9]{3} [0-9]{3}|[0-9]{2} [0-9]{7}|".


Solution

  • You need to define a regex that will match the whole string that matches your patterns as optional patterns:

    ng-pattern="/^(?:\+[0-9]{2} [0-9]{3} [0-9]{3} [0-9]{3}|[0-9]{2} [0-9]{7})?$/"
                ^^                                                           ^^
    

    Or, a bit shorter:

    ng-pattern="/^(?:\+[0-9]{2}(?: [0-9]{3}){3}|[0-9]{2} [0-9]{7})?$/"
    

    If you define the pattern in a JS file as a variable use

    var mypattern = /^(?:\+[0-9]{2}(?: [0-9]{3}){3}|[0-9]{2} [0-9]{7})?$/;
    

    Note that when using regex delimiters the anchors are required for the regex to match entire input.

    See the regex demo.

    Details