添加自定义验证指令时,验证错误消息未显示最小长度

时间:2014-05-01 12:04:37

标签: angularjs

我希望在长度小于5时显示错误消息,我尝试了类似这样的东西,但它从未显示错误消息"长度必须大于5"。当我从输入标记中删除属性equals-to时,它可以工作。如何修复指令,以便使用minlength和其他验证属性

<form id="createUserForm" class="form-horizontal row row-full" role="form" name="userForm" novalidate>    
...
<input id="newPassword" name="newPassword" ng-model="newPassword" type="password" ng-minlength="5" equals-to="confirmPassword">
    <label ng-show="userForm.newPassword.minlength" class="error">Length must be greater than 4</label>
...
</form>

的javascript

.directive('equalsTo', function() {
    return {
        require: 'ngModel',
        link: function(scope, elm, attrs, ctrl) {
            ctrl.$parsers.unshift(function(viewValue) {
                if (viewValue === scope[attrs.equalsTo]) {
                    ctrl.$setValidity('equalsTo', true);
                    return viewValue;
                } else {
                    ctrl.$setValidity('equalsTo', false);
                    return undefined;
                }
            });
        }
    };
});

1 个答案:

答案 0 :(得分:0)

您应该检查userForm.newPassword.$error.minlength,因为ngMinlength将minlength键设置为$error对象。