SoFunction
Updated on 2025-04-08

AngularJs method to verify duplicate passwords (two types)

This article will share with you two ways to verify duplicate passwords by angularjs. The specific method details are as follows:

The first type:

<label for="password">password</label>
<input  name="password" type="password" ng-model="" required>
<label for="repassword">重复password</label>
<input  name="repassword" type="password" ng-model="repassword" required>
<span style="color:red" ng-show="!=repassword">两次password不一致</span>
<input type="submit" class="btn btn-primary btn-lg" value="SAVE" ng-disabled="submit(userForm)"/>
/*JS*/
("main",function($scope){
$=function(ngFormController){
return ngFormController.$invalid; /*valid's inversion*/
};
});

This is simply to judge whether the values ​​of the two ng-models are equal. If not equal, the information controlled by the ng-show command is displayed, and so on is hidden.

But although this method is very simple, it has a serious flaw that I think is: this "password inconsistency" does not affect the internal of ngFormController. That is, even if it has incorrect passwords twice, the last submit button can still be clicked, because the $invalid of ngFormController does not think that the incorrect password twice is a mistake.

Refer to AngularJS directive 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 directive to verify whether the password is consistent between the two times.

/*Instruction creation*/
('equals',function(){
return{
require:'ngModel',
link:function(scope,elm,attrs,ngModelCtrl){
function validateEqual(myValue){
var valid = (myValue === scope.$eval());
ngModelCtrl.$setValidity('equal',valid);
return valid ? myValue : undefined;
}
ngModelCtrl.$(validateEqual);
ngModelCtrl.$(validateEqual);
scope.$watch(,function(){
ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue);
})
}
}
});
<!--html-->
<label for="password">password</label>
<input  name="password" type="password" ng-model="" required>
<label for="repassword">重复password</label>
<input  name="repassword" type="password" ng-model="repassword" <!--Note that I will use my custom commands here-->equals="" required>
<span style="color:red" ng-show="!=repassword">两次password不一致</span>
<input type="submit" class="btn btn-primary btn-lg" value="SAVE" ng-disabled="submit(userForm)"/>

In this way, with the judgment of the first method, you can perfectly verify the repeated password.

The above is the method of AngularJs to verify duplicate passwords introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!