【发布时间】:2015-06-24 23:50:18
【问题描述】:
因为 AngularJS 没有原生的“确认密码”功能,所以我今天正在编写自己的应用程序。我似乎有很多在线教程,并且正在关注 K Scott Allen 在他的Odetocode.com blog 上写的一个非常受欢迎的教程。
我的版本是这样的:
指令
angular.module('dashboard').directive('pwCheck', function() {
return {
require: 'ngModel',
scope: {
otherModelValue: '=pwCheck'
},
link: function(scope, element, attributes, ngModel) {
ngModel.$validators.pwCheck = function(modelValue) {
return modelValue == scope.otherModelValue;
};
scope.$watch('otherModelValue', function() {
ngModel.$validate();
});
}
};
});
该指令非常不言自明,它监视另一个模型值,并且每次更改时,检查两者是否相等。当他们最终这样做时,我的自定义表单验证“pwCheck”返回 true,这应该允许提交表单。返回false时,会显示字段下方的错误信息,表单无效。
HTML
<form-input icon="fa-key fa-fw">
<input type="password" name="password" ng-model="newUser.password"
placeholder="Password" ng-minlength="6" strength required/>
</form-input>
<form-input icon="fa-key fa-fw">
<input type="password" name="confirmPassword"
ng-model="newUser.confirmPassword"
placeholder="Retype Password" required pwcheck="newUser.password" />
</form-input>
<span ng-show="registrationForm.confirmPassword.$dirty">
<span ng-show="registrationForm.confirmPassword.$error.pwCheck">
Confirmation password is required, and must match.
</span>
</span>
据我所知,这应该可行。我非常严格地遵循了 Scott 制定的计划,我没有发现我的代码逻辑有任何缺陷。我正在使用 v1.2.28 的 AngularJS,也许那个版本不支持我正在做的事情。
有谁知道出了什么问题?
谢谢! 扎克
【问题讨论】:
标签: javascript angularjs validation