Angular Validator指令-永远不会调用validate方法

时间:2019-03-26 12:53:35

标签: angular validation angular-validation

我有以下验证指令:

import { Directive, Input } from '@angular/core';
import { Validator, ValidationErrors, AbstractControl, NG_VALIDATORS } from '@angular/forms';
import { isNumber } from 'util';

@Directive({
    selector: '[minMaxValidator]',
    providers: [{
        provide: NG_VALIDATORS,
        useExisting: MinMaxValidatorDirective,
        multi: true
    }]    
})

export class MinMaxValidatorDirective implements Validator {

    @Input() public minValue: number = null;
    @Input() public maxValue: number = null;

    constructor() { }

    validate(c: AbstractControl): ValidationErrors {
        let result: ValidationErrors = null;

        if (isNumber(c.value)) {
            if (this.minValue !== null && this.minValue > c.value) {
                result = { message: 'Value must be greater than ' + this.minValue };
            }

            if (this.maxValue !== null && this.maxValue < c.value) {
                result = { message: 'Value must be lower than ' + this.maxValue };
            }
        }

        return result;
    }
}

我这样使用它:

<input type="text" min-max-validator minValue="0" maxValue="1" [(ngModel)]="data.compression" />

输入呈现,但从未调用验证器中的validate方法。我在控制台中没有错误,验证器已在app.module.ts中注册

我想念什么?

1 个答案:

答案 0 :(得分:1)

您应该在输入字段上使用minMaxValidator(指令的选择器)。

<input type="text" minMaxValidator minValue="0" maxValue="1" [(ngModel)]="data.compression" />