Search code examples
angularjsng-patternangularjs-ng-pattern

ng-pattern not matching the correct regex


I am using a form to get user details. In my name input I want only alphabetic characters, spaces and apostrophe. So I created the form input like

<input placeholder="FULL NAME" type="text" ng-model="customer.name" ng-pattern="/([a-zA-Z'\s])+/" ng-required="true">

However in my form if I give input hyphen or underscore characters it is still taking as a valid input. What I am doing wrong?


Solution

  • Hey all so the solution for my problem was just to change

    ng-pattern="/([a-zA-Z'\s])+/" 
    

    to

    ng-pattern="/^([a-zA-Z'\s])+$/"
    

    So now input element looks like this

    <input placeholder="FULL NAME" type="text" ng-model="customer.name" ng-pattern="/^([a-zA-Z'\s])+$/" ng-required="true">