角形自定义验证器

时间:2020-02-17 14:21:39

标签: angular angular-forms angular-validation

我当前正在使用Angular 8,并且自定义验证程序存在问题。唯一有效的验证器是Validators.minLength(3)。 noEmptyStringValidator 不起作用,即使我可以在验证函数中打印“ here”。你可以帮帮我吗?

上下文如下:

no-empty-string.validator.ts

import { AbstractControl } from '@angular/forms';

export function noEmptyStringValidator(control: AbstractControl): { [key: string]: any } | null {
    console.log('here');

    return control.value && control.value.trim().length > 0 ? { noEmptyString: { valid: true } } : null;
}

myComponent.component.ts

...
topicLabelControl = new FormControl();
...
this.topicLabelControl.setValidators([ Validators.minLength(3), noEmptyStringValidator ]);
...
console.log(this.topicLabelControl.valid);

myComponent.component.html

<mat-form-field appearance="outline"
      (keydown.enter)="handleEnterKey()">
      <input type="text"
        matInput
        [formControl]="topicLabelControl"
        [matAutocomplete]="auto" />
      <mat-autocomplete #auto="matAutocomplete">...
      </mat-autocomplete>
    </mat-form-field>

1 个答案:

答案 0 :(得分:0)

您的逻辑似乎被颠倒了:如果输入有效,则验证器应返回null;如果无效,则其键标识错误的对象。 (该值可以是任何值,并且可以用于报告任何其他信息):

return control.value && control.value.trim().length > 0 ? null : { noEmptyString: true };