alaboudi
alaboudi

Reputation: 3403

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.

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);;
    }
};

Upvotes: 1

Views: 322

Answers (1)

Igor
Igor

Reputation: 62213

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

Upvotes: 1

Related Questions