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

2
  • Change your pattern to ^\d{4}-\d{3}-\d{4}$ ? Commented Sep 8, 2014 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: stackoverflow.com/questions/123559/… Commented Sep 8, 2014 at 19:40

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

Comments

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}$

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.