0

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

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 的值

期待快速帮助。

4

1 回答 1

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>
于 2020-02-13T22:09:40.097 回答