OGJoshZero OGJoshZero - 4 months ago 37
AngularJS Question

How Do I Keep A Validated Masked US Phone Number Validated With ng-pattern in AngularJS From Invalidating If Too Many Digits Are Entered

I have trying to figure out a way to validate an input that is masked to display US based phone numbers as

(###) ###-####
I have tried a few things and the closest thing I have found is using

<form name="phone_form" novalidate>
<input name="phone" class="phone_us" type="tel" ng-model="phone" placeholder="(555) 555-1212" ng-pattern="/^\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})$/" />
<span style="color:red" ng-show="phone_form.phone.$error.pattern">Invalid Phone Number</span>
</form>


I pulled the regex from - Angularjs dynamic ng-pattern validation - This successfully validates the input and matches the use case, it even throws the right error and displays the correct message. However as soon as you enter any digit beyond the 10 digits of the phone number the error is triggered and the input is invalid again. If I backspace one digit and add one digit again then the input validates once more as long as i dont add any more digits. The field is masked so you can not see any extra digits outside the displayed phone number and even if you try to enter 10 digits past the valid phone number all you have to do to re-validate the form successfully is backspace one digit and enter it again.

I've tried a few variations of max-length and min-length or max="#" etc. And I can't figure it out.

I am using Angular 1.5.7

A plunkr of where I am at can be found here:

http://plnkr.co/edit/Ln7SciLSpnLJRZdA0P2N?p=preview

Answer

I'd recommend you to use ngMask module.. take a look at how simple it's to use below:

angular.module('app', ['ngMask'])
 .controller('mainCtrl', function($scope) {
   
 });
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/ngMask/3.1.1/ngMask.min.js"></script>
</head>

<body ng-controller="mainCtrl">
  <form name="phone_form" novalidate>
    <input type="text" name="text" class="phone_us" ng-model="phone" placeholder="(555) 555-1212" mask="(999) 999-9999" restrict="reject">
  </form>
</body>

</html>