AngularJS比较密码字段

AngularJS比较密码字段

本文介绍了AngularJS比较密码字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用自定义指令比较两个密码字段.它似乎没有做任何事情,我也不知道如何调试它.这是我的代码:

I am trying to compare two password fields using a custom directive. It doesn't seem to be doing anything and I don't know how to debug this. Here is my code:

指令:

  .directive('pwCheck', [function () {
    return {
      require: 'ngModel',
      link: function (scope, elem, attrs, ctrl) {
        var firstPassword = '#' + attrs.pwCheck;
        elem.add(firstPassword).on('keyup', function () {
          scope.$apply(function () {
            var v = elem.val()===$(firstPassword).val();
            ctrl.$setValidity('pwmatch', v);
          });
        });
      }
    };
}])

html:

   <div class="container" ng-controller="Reset">

      <!-- P A S S W O R D -->
        <div class="form-group" ng-class="{'has-error' : reset.password.$invalid && reset.password.$dirty}">
          <div>
            <input type="password" class="form-control" name="password" placeholder="Password" ng-model="resetForm.AngularJS password" required ng-minlength="8">
            <span class="help-block has-error" ng-if="reset.password.$dirty">
              <span ng-show="reset.password.$error.required">Password is required.</span>
              <span ng-show="reset.password.$error.minlength">Password must be at least 8 characters.</span>
            </span>
          </div>
        </div>

        <!-- C O N F I R M   P A S S W O R D -->
        <div class="form-group" ng-class="{'has-error' : reset.confirmPassword.$invalid && reset.confirmPassword.$dirty}">
          <div>
            <input type="password" class="form-control" name="confirmPassword" placeholder="Confirm Password" ng-model="resetForm.confirmPassword" required pw-check="reset.password">
            <span class="help-block has-error" ng-if="reset.password.$error.pwmatch">
              <span ng-show="reset.password.$error.pwmatch">Passwords must match.</span>
            </span>
          </div>
        </div>

     </div>

推荐答案

我在注册时使用了以下指令来比较密码字段.

I use the following directive in my sign up to compare the password fields.

app.directive('validateIdentical', function ValidateIdenticalDirective(){
    return {
        restrict: 'A'
        , scope: {
            expression: '<validateIdentical'
        }
        , require: ['ngModel']
        , link: link
    };

    function link($scope, $element, $attrs, $controllers){
        var $ngModel = $controllers[0];

        $ngModel.$validators.identical = function isIdentical(modelValue){
            return $scope.expression == modelValue;
        };
    }
});

像这样使用:

<form>
    <label>Password: <input type="password" ng-model="vm.password"></label><br>
    <label>Confirm: <input type="password" ng-model="vm.confirmPassword" validate-identical="vm.password"></label>
</form>

这篇关于AngularJS比较密码字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 08:13