Reputation: 3307
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
Upvotes: 0
Views: 3869
Reputation: 345
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; }); } }; });
Upvotes: 0
Reputation: 3511
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}$
Upvotes: 0
Reputation: 16498
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>
Upvotes: 1