角度自定义验证器:

时间:2020-02-13 21:20:33

标签: angular angular-custom-validators

我当前使用的自定义验证器是:

static digitOnly(digit: string): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
        const restrict = [];
        for (let i = 0; i < parseInt(digit); i++) {
            restrict.push('0');
        }
        const val = control.value;
        if (val === null || val === '') {
            return null;
        }
        if (restrict.toString().replace(/,/g,'') === val.toString()) {
            return { 'invalidNumber': true };
        }
       const pattern = new RegExp(`^[0-9]{${digit}}$`);
        if (!val.toString().match(pattern)) {
            return { 'invalidNumber': true };
        }
        return null;
    }
}

说明:

我想在接受GPA的输入字段中添加自定义验证器,要求是: 输入的值不能大于400或为空,也不能为0或1

现在:我的自定义验证程序正在满足以下条件: 确认000为无效,这是正确的 确认0或1或数字一位无效,这是正确的

唯一的问题是它接受的值大于400

期待获得快速帮助。

1 个答案:

答案 0 :(得分:0)

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

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

export class ForbiddenValidator implements Validator {

    /**
     * Verify if the value it is allowed or not
     * @param control form control which is evaluated
     */
    validate(control: AbstractControl): { [key: string]: any } | null {
        if (control.value.length < 3 || control.value === '')
            return { 'forbidden': true };

        let num = parseInt(control.value);
        return num > 400 ? { 'forbidden': true } : null;
    }
}

这将是您的自定义验证程序指令,然后在您的模板中:

<form #form="ngForm">
  <input nz-input id="property" name="property" [(ngModel)]="someVariable 
  (ngModelChange)="onChange()" forbidden #property="ngModel">

  <div *ngIf="property.invalid && property.errors.forbidden>
       Invalid value
  </div>
</form>