【问题标题】:Angular dynamic validation only when formControl is invalid仅当 formControl 无效时才进行角度动态验证
【发布时间】:2021-11-06 04:28:50
【问题描述】:

我希望 formControl 具有updateOn: 'change' 行为,但只有在用户结束输入并且它变为无效时。

这就是我的 formGroup 的样子:

  controlValidation = '^((?!-)[A-Za-z0-9-]' + '{1,63}(?<!-)\\.)' + '+[A-Za-z]{2,3}';

  campaignForm: FormGroup = this.formBuilder.group(
    { control: [null, Validators.pattern(this.controlValidation)]},
    { updateOn: 'blur' }
  );

模板看起来像这样

 <div class="form-group">
   <input type="text" formControlName="advertiserDomain" />
   <div *ngIf="campaignForm.get('control').invalid">
      Error message that should only display reactivly BUT only once the user finished writing for the first time
   </div>
</div>

【问题讨论】:

  • 您只想在用户输入完输入控件后才显示错误消息?
  • 您可以在模糊上使用更新,但也可以将空输入验证为有效值

标签: angular form-control formgroups


【解决方案1】:

我不确定你所问的确切含义,但我会尝试回答:

基本上formGroup 无法知道用户是否开始或结束输入其单词或句子,这就是为什么每次更改都会触发change。考虑到连续输入了许多字符,您仍然可以进行破解,您可以添加一个setTimeout,当在某个延迟(比如说 1 秒)之前按下某个键并且延迟达到 1 秒时使用方法updateValueAndValidity() 手动触发表单的有效性检查。

以下代码尚未经过测试,但这是主要思想。

你的html:

<input type="text" (input)="keyPress()" formControlName="advertiserDomain" />

你的 ts:

timeout;

keyPress(){

  clearTimeout(this.timeout);

  this.timeout = setTimeout( _ => {
     this.campaignForm.updateValueAndValidity();
  }, 1000);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 2012-12-22
    相关资源
    最近更新 更多