1

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.

html

<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="checkout.cf.exp">

controller function

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

    //add separator
    if(vm.cf.exp.length==2){//-----> cannot process since ngPattern makes exp undefined till pattern is met
        vm.cf.exp = vm.cf.exp.substring(0,2) + separator;
    }
    //remove separator
    if(vm.cf.exp.length==4){
        vm.cf.exp = vm.cf.exp.substring(0,1);;
    }
};
alaboudi
  • 3,187
  • 4
  • 29
  • 47

1 Answers1

1

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(vm.cf.exp)); // set validity to whatever name you want, I used the name pattern
};
Igor
  • 60,821
  • 10
  • 100
  • 175
  • can I use from.exp by just specifying the form name and field name? Do I not have to declare them as angular models? I am fairly new to angular. Id appreciate if you can clarify this. – alaboudi Aug 23 '16 at 21:53
  • @alaboudi - Correct. You can also access the from from the controller and its corresponding fields by name (there is more than 1 way to skin a cat :)). – Igor Aug 24 '16 at 00:13
  • Thank you so much. I have implemented your solution. – alaboudi Aug 24 '16 at 03:40