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:
两次密码不一致 /*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); }) } } }); equals="user.password" required> 两次密码不一致
In this way, coupled with the judgment of the first method, repeated passwords can be perfectly verified.