2015-03-03 104 views
0

我想匹配两个文本字段密码whick看起来是这样的:预期Angularjs:匹配密码太快?

pwCheck.js

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

accounts.html

<label>{{label.password}}</label> 
    <input type="password" class="form-control" id="pw1" name="pw1" ng-model-options="{updateOn:'blur'}" ng-model="user.password" required ></input> 

<label>{{label.retypePassword}}</label> 
    <input type="password" class="form-control" id="pw2" name="pw2" ng-model-options="{updateOn:'blur'}" ng-model="pw2" ng-required="" pw-check="pw1"></input> 

<div class="msg-block" ng-show="signupform.$error"><img src = "./images/error-icon.png" width = "25" height = "25" ng-show="signupform.pw2.$error.pwmatch"></img><span class="msg-error" ng-show="signupform.pw2.$error.pwmatch">Passwords don't match.</span></div> 

上面的代码工作正常,但给一个可怕的用户体验。发生这种情况是因为当我输入第一个文本字段时,即使用户没有完成输入,“密码不匹配”消息也会显示。

问题是,在用户输入完成之前验证发生得太快。

我试图通过加入ng-model-options="{updateOn:'blur'}"来解决这个问题,但问题仍然存在。

帮助!在此先感谢

+2

为什么不把'keyup'改成'模糊' – 2015-03-03 04:09:35

+0

我试过了,谢谢它现在正在工作。 。 – 2015-03-03 04:13:32

+1

如果使用angular 1.3+,您还可以使用ng-model-options debounce选项进行研究。 – 2015-03-03 04:23:22

回答

1

使用模糊,而不是键。 尝试以下操作:

angular.module('installApp') 
.directive('pwCheck', function ($http) { 
    return { 
    require: 'ngModel', 
    link: function (scope, elem, attrs, ctrl) { 
     var firstPassword = '#' + attrs.pwCheck; 
     elem.on('blur', function() { 
      scope.$apply(function() { 
       ctrl.$setValidity('pwmatch', elem.val() === $(firstPassword).val()); 
      }); 
     }); 
     } 
    } 
}); 

注意:上ELEM删除add方法。会抛出错误,因为在元素上没有定义添加方法。