2015-10-17 121 views
0

试图在角度js中使用自定义指令来匹配密码。尽管我已经看过几本谷歌教程,但我无法完成它的工作。我创建了一个显示它不在plunker工作的Plunker。密码匹配angularjs验证

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。

回答

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> 
+0

唉唉那些该死的破折号。我改变了这一点,一切工作都很完美,除非如上所述,密码至少在6个字符之前是未定义的。这里最好的做法是什么?如果compareModel(第一个密码)是<6个字符,我应该只有“confirmPassword”验证器有效吗? – jekelija

+0

@jekelija我可能会显示密码字段的验证消息,通知用户密码太短或太长。这样做很明显为什么没有执行密码确认验证 - 因为要确认的密码无效。 –

+3

@BohuslavBurghardt此外,你不应该使用解析器和格式化器来验证字段。验证因此而存在。这是一个使用一个叉子:http://plnkr.co/edit/ogJIlMyqWrOlXpyv9psB?p=preview –