Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two input values in a form validation with AngularJS

I am trying to do a form validation using AngularJS. I am especially interested in comparing two values. I want the user to confirm some data he entered before he continues. Lets say I have the code below:

<p>     Email:<input type="email" name="email1" ng-model="emailReg">     Repeat Email:<input type="email" name="email2" ng-model="emailReg2"> <p> 

and then I can use validation with:

<span ng-show="registerForm.email1.$error.required">Required!</span> <span ng-show="registerForm.email1.$error.email">Not valid email!</span> <span ng-show="emailReg !== emailReg2">Emails have to match!</span>  <-- see this line 

registerForm.$valid will react correctly as to the text in inputs except I do not know how to use comparison within this validation to force the emails to be the same before allowing the user to submit the form.

I would love to have a solution without custom directives, but if this can't be achieved without it I will deal with it. Here is an answer that addresses similar issue with a custom directive.

Any help appreciated, thank you

like image 927
trainoasis Avatar asked Mar 04 '14 13:03

trainoasis


1 Answers

You should be able to use ng-pattern/regex for comparing 2 input values

Email:<input type="email" name="email1" ng-model="emailReg"> Repeat Email:<input type="email" name="email2" ng-model="emailReg2" ng-pattern="emailReg"> 

and validation with:

<span ng-show="registerForm.email2.$error.pattern">Repeat Email should have the same value with email!</span> 
like image 168
Henry Neo Avatar answered Sep 20 '22 20:09

Henry Neo