AngularJS password confirmation noMatch working but form is $invalid?

可紊 提交于 2019-12-08 09:37:19

问题


I am using this code to make password input and confirm password input to match correctly

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>

Code is working fine but when I pass form to ng-submit function it always says invalid at confirm password field . I check this form in console only confirm password field has $valid = false and $invalid = true . Need help what is wrong here.

Here is the console


回答1:


I don't see why you use $parsers instead of $validators? Parsers are used for formatting not for validating an input field! Here's my solution:

/**
 * 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;
      };
    }
  };
});

The $error attribute is named match not noMatch because that would be double negative.




回答2:


The specific error you're seeing is because you are using $parsers incorrectly, you should be using $validators as mentioned in Betty St's answer.

From the angular documentation for $Parsers

Returning undefined from a parser means a parse error occurred.

Note that the function you unshift to $parsers has no return, meaning it returns undefined, which is interpreted as a parse error. (exactly as the $error object indicates)



来源:https://stackoverflow.com/questions/30467088/angularjs-password-confirmation-nomatch-working-but-form-is-invalid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!