This article will share with you two methods for verifying repeated passwords in angularjs. The details of the specific method are as follows:
The first one:
<label for="password">密码</label> <input id="password" name="password" type="password" ng-model="user.password" required> <label for="repassword">重复密码</label> <input id="repassword" name="repassword" type="password" ng-model="repassword" required> <span style="color:red" ng-show="user.password!=repassword">两次密码不一致</span> <input type="submit" class="btn btn-primary btn-lg" value="SAVE" ng-disabled="submit(userForm)"/> /*JS*/ app.controller("main",function($scope){ $scope.submit=function(ngFormController){ return ngFormController.$invalid; /*valid的取反*/ }; });
This is simply to judge whether the values of the two ng-models are equal. If they are not equal, the information controlled by the ng-show command will be displayed. , etc. will be hidden.
But although this method is very simple, it has a flaw that I think is more serious: this "password inconsistency" does not affect the internals of ngFormController. In other words, even if the password is incorrect twice, the final submit button can still be clicked, because $invalid of ngFormController does not consider incorrect passwords twice as an error.
Refer to the AngularJS instructions ng-maxlength, etc., but they can cause $invalid detection, so to solve the above problem, I think one of the ways is to create a custom instruction to verify whether the two passwords are consistent.
/*指令创建*/ app.directive('equals',function(){ return{ require:'ngModel', link:function(scope,elm,attrs,ngModelCtrl){ function validateEqual(myValue){ var valid = (myValue === scope.$eval(attrs.equals)); ngModelCtrl.$setValidity('equal',valid); return valid ? myValue : undefined; } ngModelCtrl.$parsers.push(validateEqual); ngModelCtrl.$formatters.push(validateEqual); scope.$watch(attrs.equals,function(){ ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue); }) } } }); <!--html--> <label for="password">密码</label> <input id="password" name="password" type="password" ng-model="user.password" required> <label for="repassword">重复密码</label> <input id="repassword" name="repassword" type="password" ng-model="repassword" <!--注意这里将要使用我自定义的指令-->equals="user.password" required> <span style="color:red" ng-show="user.password!=repassword">两次密码不一致</span> <input type="submit" class="btn btn-primary btn-lg" value="SAVE" ng-disabled="submit(userForm)"/>
In this way, coupled with the judgment of the first method, repeated passwords can be perfectly verified.