AngularJS密码验证 [英] AngularJS password validation
问题描述
我正在从教程使用Angular,节点和令牌身份验证创建应用程序"中学习.而且我被卡住了.我在这里找到了这段代码:
i'm learning from tutorial "Creating Apps With Angular, Node, and Token Authentication". And i've stuck. I found this code there:
html
<form name="register" class="form-signin" novalidate>
<h1 class="form-signin-heading text-muted">Register</h1>
<input type="email" ng-model="email" name="email"
class="form-control" placeholder="Email address"
required autofocus>
<p class="help-block"
ng-show="register.email.$dirty && register.email.$invalid">
Please enter a proper email.
</p>
<input type="password" name="password" ng-model="password"
class="form-control" placeholder="Password" required>
<input type="password" name="password_confirm" ng-model="password_confirm"
class="form-control" placeholder="Confirm Password"
validate-equals="password">
<p class="help-block"
ng-show="register.password_confirm.$invalid && register.password_confirm.$dirty">
please match the passwords.
</p>
<button ng-disabled="register.$invalid" class="btn btn-lg btn-primary btn-block" type="submit">
Submit
</button>
</form>
和js
angular.module('myApp', []).directive('validateEquals', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
function validateEqual(value) {
var valid = (value === scope.$eval(attrs.validateEquals));
ngModelCtrl.$setValidity('equal', valid);
return valid ? value : undefined;
}
ngModelCtrl.$parsers.push(validateEqual);
ngModelCtrl.$formatters.push(validateEqual);
scope.$watch(attrs.validateEquals, function() {
ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue);
});
}
};
});
根据视频显示的此指令应为我提供对password
和password_confirm
输入的正确双向验证,但不能(在视频显示中它确实起作用,我很困惑).当我更改password_confirm
的值时,它验证得很好,但是当我更改password
时,验证不起作用.这是 plunker .问题:该代码有什么问题?而我该如何解决?
this directive according to the video should give me a proper two-way validation for password
and password_confirm
inputs, but it doesn't (on video it does work, i'm confused). It validates well, when i change value of password_confirm
but when i change password
, validation not work. Here is plunker plunker. Question: What's wrong with that code? And how should i fix it?
推荐答案
找到了解决方案,这要归功于JB Nizet:)
Solution found, Thanks to JB Nizet :)
解决方案:
angular.module('learningAngularApp')
.directive('validateEquals', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
ngModelCtrl.$validators.validateEqual = function(modelValue, viewValue) {
var value = modelValue || viewValue;
var valid = (value === scope.$eval(attrs.validateEquals));
return valid;
}
scope.$watch(attrs.validateEquals, function () {
ngModelCtrl.$validate();
});
}
};
});
这篇关于AngularJS密码验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!