0

Hi I have an input field where I want to do validation such that input only has numbers but with dashes and 11 number maximum

  i.e  1233-224-1234

I have following validation applied that only accepts numbers

  <input ng-pattern="customNum" ng-model=value.id />
   In my controller I have 

function myCtrl($scope) {
    $scope.customNum = /^\d+$/;
}

Please let me know how i can update this so that 13 digits are entered out of which 11 are numbers and two are dashes. Thanks

Paolo Moretti
  • 54,162
  • 23
  • 101
  • 92
J. Davidson
  • 3,297
  • 13
  • 54
  • 102
  • Change your pattern to `^\d{4}-\d{3}-\d{4}$` ? – hwnd Sep 08 '14 at 19:40
  • If you are looking for a phone number validation you can use `ng-pattern` with a regex. You can find examples of that here: http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation – drew_w Sep 08 '14 at 19:40

3 Answers3

1

Please see here :http://jsbin.com/talaz/1/

<form name="form" class="css-form" novalidate>      

        <input type="text" ng-model="code" name="code" ng-pattern='/^\d{4}-\d{3}-\d{4}$/'    />Code :{{code}}<br />        
        <span ng-show="form.size.$error.pattern ">
          The code need to falow that 1234-123-1234 pattern</span>
 </form>
sylwester
  • 16,498
  • 1
  • 25
  • 33
0

You can try this if the digits are not fixed:

^\d+[-]\d+[-]\d+$

If your digits are fixed then :

^\d{4}-\d{3}-\d{4}$
Alok Chaudhary
  • 3,481
  • 1
  • 16
  • 19
0

If you want a reusable validation that you can use in a lot of places and change in one place you can use a custom validator directive. I've called it a creditcard validator just for the example.

<form name="form">
   <input type="text" ng-model="user.creditcard" name="creditcardNumber" validate-creditcard>
   <span ng-show="form.creditcardNumber.$error.creditcard">
      This is not a valid credit card number.
   </span>
</form>


 app.directive('validateCreditcard', function() {
      var creditcardRegex = /^\d{4}-\d{3}-\d{4}$/;

      return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, el, attr, ngModelCtrl) {
          ngModelCtrl.$parsers.unshift(function(input) {
            var valid = creditcardRegex.test(input);
            ngModelCtrl.$setValidity('creditcard', valid);
            return valid;
          }); 
        }
      };
    });

example on plnkr

yairhaimo
  • 345
  • 2
  • 10