AngularJS自定义验证无效

时间:2015-03-02 17:47:30

标签: javascript angularjs validation angularjs-directive

我有三个输入,每个输入都需要自定义验证。 所以我做了这样的指令来验证它们:

function CardValidator(ValidatorService) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function($scope, $element, $attrs, ngModel) {
            $element.on('keyup', function(e) {
                var isValid = ValidatorService.checkValidity(e.target.value);
                ngModel.$setValidity($attrs.ngModel, isValid);
            });
        }
    }
}

这是我的HTML:

    <form method="post" autocomplete="off" name="formCard" novalidate>
        <div class="row field">
            <i class="icon icon-cpf"></i>
            <input type="text" ng-model="vm.card.number" name="card" card-validator mask="9999  9999  9999  9999" required>
            <label>cartão</label>
        </div>

        <div class="group">
            <div class="row field field-medium left">
                <i class="icon icon-cpf"></i>
                <input type="text" ng-model="vm.card.expireDate" card-valid-thru-validator mask="99/99" required>
                <label>validade MM/AA</label>
            </div>

            <div class="row field field-medium field-last right">
                <input type="text" ng-model="vm.card.cvv" card-security-code-validator required>
                <label>CVV</label>
            </div>
        </div>      
    </form>

以下是所有三个字段有效的HTML:

<form method="post" autocomplete="off" name="formCard" novalidate="" class="ng-dirty ng-valid-vm.card.number ng-valid-vm.card.expire-date ng-valid-required ng-valid ng-valid-vm.card.cvv">

输入正常,AngularJS将ng-validng-invalid放在应有的位置。但是form整体上没有用。当我调用form.$valid时,它总是返回true,即使3个输入字段位于ng-valid

0 个答案:

没有答案