【问题标题】:AngularJS password confirmation noMatch working but form is $invalid?AngularJS 密码确认 noMatch 工作但表单是 $invalid?
【发布时间】:2015-05-26 19:19:27
【问题描述】:

我正在使用此代码进行密码输入并确认密码输入正确匹配

Javascript:

    var app = angular.module('app', []);
app.directive('validPasswordC', function() {
  return {
    require: 'ngModel',
    scope: {

      reference: '=validPasswordC'

    },
    link: function(scope, elm, attrs, ctrl) {
      ctrl.$parsers.unshift(function(viewValue, $scope) {

        var noMatch = viewValue != scope.reference
        ctrl.$setValidity('noMatch', !noMatch)
      });

      scope.$watch("reference", function(value) {;
        ctrl.$setValidity('noMatch', value === ctrl.$viewValue);

      });
    }
  }
});
 app.controller('homeCtrl', function($scope) {
     $scope.submit= function (form) {
        if(form.$valid)
        alert('in');
        else
            alert('out');
    }
    });

HTML:

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="homeCtrl">
    <p>Password:{{formData.password}}</p>
    <form name="signupForm" ng-submit="submit(signupForm)">
      <div class="fieldset" ng-class="{'has-error':formData.password.$invalid && !formData.password.$pristine}">
        <label>Password</label>
        <input type="password" id="password" name="password" ng-model="formData.password" ng-minlength="8" ng-maxlength="20" ng-pattern="/(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z])/" placeholder="password" required />

        <p ng-show="signupForm.password.$error.required" class="error">*</p>
        <p ng-show="signupForm.password.$error.minlength" class="error">
          Passwords must be between 8 and 20 characters.</p>
        <p ng-show="signupForm.password.$error.pattern" class="error">
          Must contain one lower &amp; uppercase letter, and one non-alpha character (a number or a symbol.)</p>
      </div>

      <div class="fieldset" ng-class="{'has-error':formData.password_c.$invalid && !formData.password_c.$pristine}">
        <label for="password_c">Confirm Password</label>
        <input type="password" id="password_c" name="password_c" ng-model="formData.password_c" placeholder="confirm password" valid-password-c="formData.password" required />

        <p ng-show="signupForm.password_c.$error.noMatch" class="error">Passwords do not match.</span>
          <p ng-show="signupForm.password_c.$error.required" class="error">*</p>
      </div>
    </form>
  </div>
</div>

代码工作正常,但是当我将表单传递给 ng-submit 函数时,它总是在确认密码字段处显示无效。我在控制台中检查此表单仅确认密码字段具有 $valid = false 和 $invalid = true 。需要帮助这里有什么问题。

这是控制台

【问题讨论】:

  • 你看过$error吗?这应该可以准确地告诉您失败的原因
  • 那里真的很难理解
  • 您可以将其添加到问题中吗?也许有人可以帮助您理解这一点
  • 添加了确认密码字段的图片
  • 好的,从 $error 中我们可以看到 parse 设置为 true。这意味着原因在于您的 $parsers 函数。我看到你传入函数 $scope,然后引用范围。是不是打错字了?

标签: javascript angularjs validation angularjs-validation


【解决方案1】:

我不明白你为什么使用$parsers 而不是$validators?解析器用于格式化而不是验证输入字段!这是我的解决方案:

/**
 * Validator for matching two inputs.
 * The given attribute is the value to match the own modelValue.
 * @example
 *   <input name="passwordConfirm" type="password" ng-model="passwordConf" validate-match="newPassword">
 */
app.directive('validateMatch', function () {
  return {
    require: 'ngModel',
    scope: {
      validateMatch: '='
    },
    link: function(scope, element, attrs, ngModel) {

      scope.$watch('validateMatch', function() {
        ngModel.$validate(); // validate again when match value changes
      });

      ngModel.$validators.match = function(modelValue) {
        if (!modelValue || !scope.validateMatch || ngModel.$error.minlength) {
          return true;
        }
        return modelValue === scope.validateMatch;
      };
    }
  };
});

$error 属性被命名为 match 而不是 noMatch,因为这将是双重否定。

【讨论】:

  • ngModel.$validators.match 函数检查给定模型和实际模型值的相等性。
  • signupForm.passwordConfirm.$error.match 这适用于错误
  • 它也适用于signupForm.$invalid 或signupForm.passwordConfirm.$invalid!
  • 我还建议对表单组使用指令(如果您使用引导程序)@see stackoverflow.com/a/22658021/595152
【解决方案2】:

您看到的具体错误是因为您错误地使用了 $parsers,您应该使用 Betty St 的回答中提到的 $validators。

来自角度文档for $Parsers

从解析器返回 undefined 意味着发生了解析错误。

请注意,您取消转移到 $parsers 的函数没有返回,这意味着它返回未定义,这被解释为解析错误。 (正如 $error 对象所指示的那样)

【讨论】:

  • Betty St 的回答详细说明了如何使用匹配验证器。它只需要更新为您的特定命名。
猜你喜欢
  • 2015-01-06
  • 2017-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-19
  • 2014-10-18
  • 2021-03-19
  • 2018-09-26
相关资源
最近更新 更多