【问题标题】:Custom password validation directive not applying自定义密码验证指令不适用
【发布时间】:2017-11-13 16:38:46
【问题描述】:

我正在使用 AngularJS,我想创建一个密码确认字段来检查两个条目是否匹配。为此,我使用了本教程中的自定义指令:http://odetocode.com/blogs/scott/archive/2014/10/13/confirm-password-validation-in-angularjs.aspx。

由于某种原因,匹配检查没有给出任何结果。当我输入不同的密码时,它仍然认为这些字段是有效的。我想我遗漏了关于 AngularJS 中自定义指令的使用的一些内容,但这有点令人困惑,因为我使用的代码与教程中的完全相同。

我也在这里查看了关于 SO 的相关问题,但也没有运气。

HTML:

<div ng-app="myApp">
  <h1>Register!</h1>
    <form name="registrationForm" novalidate>
       <div class="form-group">
            <label>User Name</label>
            <input type="text" name="username" class="form-control" ng-model="registration.user.username" required />
            <p ng-show="registrationForm.username.$error.required">Required<br/><br/></p>
        </div>
        <div class="form-group">
            <label>Password</label>
            <input type="password" name="password" class="form-control" ng-model="registration.user.password" required />
            <p ng-show="registrationForm.password.$error.required">Required<br/><br/></p>
        </div>
        <div class="form-group">
            <label>Confirm Password</label>
            <input type="password" name="confirmPassword" class="form-control" ng-model="registration.user.confirmPassword" required compare-to="registration.user.password" />
            <p ng-show="registrationForm.confirmPassword.$error.required">Required<br/><br/></p>
            <p ng-show="registrationForm.confirmPassword.$error.compareTo">Passwords must match !</p>
        </div>
        <div class="form-group">
            <button type="submit" class="btn btn-primary">Register!</button>
        </div>
    </form>
</div>

JS:

angular.module('myApp', [])

.directive('compareTo', function(){
      return {
        require: "ngModel",
        scope: {
            otherModelValue: "=compareTo"
        },
        link: function(scope, element, attributes, ngModel) {

            ngModel.$validators.compareTo = function(modelValue) {
                return modelValue == scope.otherModelValue;
            };

            scope.$watch("otherModelValue", function() {
                ngModel.$validate();
            });
        }
      };
    })

JSFiddle 显示问题:http://jsfiddle.net/ptb01eak/

教程中的工作 Plunkr:http://plnkr.co/edit/FipgiTUaaymm5Mk6HIfn?p=preview

感谢您的帮助!

【问题讨论】:

  • 上述 plunker 和 fiddle 代码之间有很多不同之处。只要确保没有差异

标签: javascript angularjs passwords


【解决方案1】:

问题来自您的 AngularJS 版本,我在 jsfiddle 中将其更新为:AngularJS 1.5.6 (CDN link) 并且可以正常工作 (new jsfiddle)。

【讨论】:

    猜你喜欢
    • 2017-05-26
    • 2014-03-07
    • 2015-01-22
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多