alaboudi alaboudi - 4 years ago 143
AngularJS Question

issue with ngPattern

I am trying to design a nifty expiration date input on a credit card checkout form that will automatically insert a " / " between expiration month and year while the user is typing. The model no longer picks up the input value since I have introduced ngPattern validation to the input. Angular only allows a model to pick up the input value once the validation has succeeded. This basically makes my nifty feature not work due to my code. Can someone find a way around this. below is my code.


<input ng-keyup="checkout.updateExp()" class="form-control" type="text" maxlength="7" placeholder="mm / yy" required autocomplete="off" name="exp" ng-pattern="/\d{2}\s\/\s\d{2}/" ng-model="">

controller function

vm.updateExp = function(){
var separator=" / ";

//add separator
if({//-----> cannot process since ngPattern makes exp undefined till pattern is met =,2) + separator;
//remove separator
if({ =,1);;

Answer Source

Why not validate it manually using a regular expression instead of having it done using ng-pattern? You can set the $validity of the field manually just like angular would do it using ng-pattern.

In the html add

ng-keyup="checkout.updateExp(form.exp)" name="exp"

form.exp is the form and then the name of the input field. I do not know what the form name is so you will have to replace it accordingly.

vm.updateExp = function(formModel){
    /* existing code omitted */
    var expression = /\d{2}\s\/\s\d{2}/; // create RegEx
    formModel.$setValidity("pattern", expression.test(; // set validity to whatever name you want, I used the name pattern
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download