密码匹配angularjs验证

时间:2015-10-17 21:23:42

标签: angularjs angularjs-directive angular-directive

尝试使用角度js中的自定义指令匹配密码。虽然我已经查看了几个谷歌教程,但我无法让它工作。我创建了一个Plunker,显示它无法在plunker工作。

HTML:

    <div class="form-group" ng-class="{ 'has-error': form.password.$invalid && !form.username.$pristine }">
        <label for="password">Password</label>
        <input type="password" name="password" id="password" class="form-control" ng-model="user.password" required ng-minlength="6" ng-maxlength="12"/>
    </div>
    <div class="form-group" ng-class="{ 'has-error': form.confirm-password.$invalid && !form.confirm-password.$pristine }">
        <label for="confirm-password">Confirm Password</label>
        <input type="password" name="confirm-password" id="confirm-password" class="form-control" ng-model="user.confirmpwd" required equal="{{user.password}}"/>
        <span ng-show="user.confirmpwd.$error.equal" class="help-block">Password does not match above</span>
    </div>

JAVASCRIPT:

app.directive('equal', [
function() {

var link = function($scope, $element, $attrs, ctrl) {

  var validate = function(viewValue) {
    var comparisonModel = $attrs.equal;
      console.log(viewValue + ':' + comparisonModel);

    if(!viewValue || !comparisonModel){
      // It's valid because we have nothing to compare against
      ctrl.$setValidity('equal', true);
    }

    // It's valid if model is lower than the model we're comparing against
    ctrl.$setValidity('equal', viewValue === comparisonModel );
    return viewValue;
  };

  ctrl.$parsers.unshift(validate);
  ctrl.$formatters.push(validate);

  $attrs.$observe('equal', function(comparisonModel){
        return validate(ctrl.$viewValue);
  });

};

return {
  require: 'ngModel',
  link: link
};
}]);

问题似乎是在自定义指令周围,它似乎没有正确绑定到ngModel项目?我觉得我必须遗漏一些简单的东西,我刚开始学习AngularJS。

1 个答案:

答案 0 :(得分:4)

密码字段绑定应该有效,但您要验证密码字段的长度至少应为6个字符,这意味着只有在输入6个或更多字符后才会绑定到模型。在此之前,它将是undefined,这是我在console.log语句中得到的结果。

然而还有其他问题。系统不会显示错误消息,因为您的字段名称为confirm-password。您应该将其命名为confirmPassword或不带破折号的内容。该名称由Angular用作对象属性,JavaScript对象键不能包含短划线。

因此,表单的密码确认部分应如下所示:

<div class="form-group" ng-class="{ 'has-error': form.confirmPassword.$invalid && !form.confirmPassword.$pristine }">
    <label for="confirm-password">Confirm Password</label>
    <input type="password" name="confirmPassword" id="confirm-password" class="form-control" ng-model="user.confirmpwd" required equal="{{user.password}}"/>
    <span ng-show="form.confirmPassword.$error.equal" class="help-block">Password does not match above</span>
</div>
相关问题