Reputation: 452
I have two simple inputs
on my form. I need them to match but since they are phone numbers, I added a uimask
to them so the user can only enter numbers and it is auto formatted as (999)-999-9999
.
My issue is that all of my attempts at ensuring the two fields match each other are coming up wrong. I can never get them to match (from a model perspective) if I am using uimask
. If I remove uimask
from my form then the matching works as expected.
Please review this codepen to see the issue occurring. Am I missing something? Or am I simply not allowed to pattern match two fields that use uimask
?
Here is a shortened example in case the codepen doesn't work. I am always seeing the error message of doesnt match
even though the two fields have identical values in them.
<form name="demo" class="container">
<input class="form-control" type="text"
id="phone"
name="phone"
ng-model="x"
ui-mask="(999) 999-9999" />
<input class="form-control" type="text"
id="phone2"
name="phone2"
ng-model="y"
ui-mask="(999) 999-9999"
ng-pattern="(x)"/>
<div ng-messages="demo.phone2.$error" role="alert">
<div class="text-danger" ng-message="pattern">doesnt match.</div>
</div>
Upvotes: 1
Views: 420
Reputation: 6486
You are misunderstanding how ng-pattern
works. ng-pattern
is a regex validator, which ui-mask
already addresses to a small extent. In your example, the second input is literally looking to match the the regex /^(x)$/
, which would match the literal string "x"
, not the variable contained there.
If you want to verify that the two inputs match, you'll have to add your own validation. A simple way of doing this is just adding ng-change
events to manually manipulate the form element validity with $setValidity(validationErrorKey, isValid)
. I'd personally put this kind of kind in the controller for your form, but these adaptations to the code in your codepen should work.
<input class="form-control" ng-class="{requiredControl:demo.phone.$dirty && demo.phone.$invalid}" type="text"
id="phone"
name="phone"
ng-model="x"
ng-change="demo.phone2.$setValidity('match', x==y)"
ng-required="true"
ui-options="{clearOnBlur:false}" ui-mask-placeholder
ui-mask-placeholder-char="_"
ui-mask="(999) 999-9999" />
<input class="form-control" ng-class="{requiredControl:demo.phone.$dirty && demo.phone.$invalid}" type="text"
id="phone2"
name="phone2"
ng-model="y"
ng-required="true"
ng-change="demo.phone2.$setValidity('match', x==y)"
ui-options="{clearOnBlur:false}" ui-mask-placeholder
ui-mask-placeholder-char="_"
ui-mask="(999) 999-9999"/>
And then just make sure that you refer the the proper error label in ng-messages
. I used a new error labeled 'match'
instead of the built-in 'pattern'
to better communicate what the validation is for.
<div ng-messages="demo.phone.$error" role="alert" ng-if="demo.phone.$dirty">
<div class="text-danger" ng-message="match">doesnt match.</div>
</div>
Upvotes: 1