0

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

Community
  • 1
  • 1
OGZCoder
  • 285
  • 1
  • 5
  • 15
  • Still thinking of the best way to solve this, but you'll see that this is (in part) due to `mask.js`...when removing `$('.phone_us').mask('(000) 000-0000');`, you'll see that the `phone` value is actually longer than 10 digits (and therefore invalid) but looks valid because of `.mask()`. – Sam Jul 18 '16 at 22:24
  • As far as a solution, you may be best off making a [custom directive to prevent non-numbers](http://stackoverflow.com/a/15556249/703229) rather than using `ngPattern` to validate. This, in my opinion, will work nicely with `.mask()`. – Sam Jul 18 '16 at 22:26

1 Answers1

1

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>
developer033
  • 24,267
  • 8
  • 82
  • 108