【问题标题】:Angular Form Custom ValidatorsAngular 表单自定义验证器
【发布时间】:2020-02-17 14:21:39
【问题描述】:

我目前正在使用 Angular 8,但我遇到了自定义验证器的问题。唯一有效的验证器是 Validators.minLength(3)。 noEmptyStringValidator 不起作用,即使我可以将“这里”打印到验证器函数中。你可以帮帮我吗?

上下文如下:

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>

【问题讨论】:

    标签: angular angular-forms angular-validation


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-07
      • 2020-01-13
      • 1970-01-01
      • 2022-01-23
      • 2018-05-28
      • 2017-08-28
      • 2018-05-23
      • 2018-01-26
      相关资源
      最近更新 更多