【问题标题】:Angular reactive form custom validation : update on change not working on first timeAngular 反应式表单自定义验证:更新第一次无法正常工作的更改
【发布时间】:2021-04-08 05:43:14
【问题描述】:

我在我的响应式表单中实现了自定义验证,基本上,当字段长度达到一定限制时会显示错误。

this.formGroup = new FormBuilder().group({
     comment: [null, {
        validators: [ValidateCommentLength],
        updateOn: 'change'
      }]
  })

HTML

<textarea
            autocomplete="off"
            maxlength="3600"
            nxInput
            (ngModelChange)="valueChange($event)"
            type="text"
            [formControlName]="'comment'"
          ></textarea>
          <nx-error nxFormfieldError *ngIf="formGroup.get('comment').invalid" appearance="text">
            Maximum comment length is exceeded 
          </nx-error>
        </nx-formfield>

但是验证不会在第一次输入更改时触发,以后的更改将起作用

更新验证器

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

const MAX_LENGTH =  2;

    export function ValidateCommentLength(control: AbstractControl) {
    
        if (control.value) {
            if (!control.value.replace(/\s/g, '').length) {
                return null;
            }
            const  remaining = MAX_LENGTH - control.value.length;
            if (!remaining || Math.sign(remaining) === -1) {
                return { CommentError: true };
           }
    
        }
        return null;
    }

【问题讨论】:

  • 请为ValidateCommentLength添加代码
  • I reproduce your scenario,怎么了?
  • @OwenKelvin 添加了验证器
  • @MehdiShakeri 不正确我有自定义表单验证器,请检查更新后的问题
  • @iambatman nx-error 来自哪个库?

标签: angular angular-reactive-forms


【解决方案1】:

问题

问题是nx-error 只会在输入被触摸时显示。但是只有当我们模糊了表单时才会触及输入

解决方案

验证器使输入无效后,手动触摸触发器

export function ValidateCommentLength(control: AbstractControl) {
  if (control.value) {
    if (!control.value.replace(/\s/g, "").length) {
      return null;
    }
    const remaining = MAX_LENGTH - control.value.length;
    if (!remaining || Math.sign(remaining) === -1) {
      control.markAsTouched()
      return { CommentError: true };
    }
  }
  return null;
}

在上面我刚刚添加了control.markAsTouched(),现在验证工作如您所愿

See Demo Here

【讨论】:

    猜你喜欢
    • 2019-11-17
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    • 2020-04-24
    • 2020-04-21
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    相关资源
    最近更新 更多