You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让ng-zorro-antd表单在输入框blur后才显示验证提示?

这个需求我太熟了!之前做项目的时候也碰到过,用户一输入就弹错误提示确实有点不友好,其实结合Angular表单的内置状态和ng-zorro的特性,完全可以轻松实现“首次离开输入框再显示验证提示”的效果,给你两种实用方案:

方案一:直接利用Angular表单的touched状态(快速实现)

Angular的表单控件自带touched属性——当用户首次离开输入框(触发blur事件)后,这个属性会自动变为true。我们只需要给nz-error-tip加个显示条件,只有当控件无效且已经被触碰过(或者表单已提交)时,才展示错误提示。

示例代码:

<form [formGroup]="userForm" #formRef="ngForm">
  <nz-form-item>
    <nz-form-label>用户名</nz-form-label>
    <nz-form-control>
      <input nz-input formControlName="username" placeholder="请输入用户名" />
      <!-- 只在控件无效 + (已触碰/表单提交) 时显示错误 -->
      <nz-error-tip *ngIf="userForm.get('username')?.invalid && (userForm.get('username')?.touched || formRef.submitted)">
        用户名不能为空,且长度至少3位
      </nz-error-tip>
    </nz-form-control>
  </nz-form-item>

  <button nz-button type="submit">提交表单</button>
</form>

这种方式无需额外写逻辑,直接通过模板条件判断就能搞定,适合单个表单或者少量控件的场景。

方案二:自定义指令统一处理(全局复用)

如果你的项目里有大量表单需要这个逻辑,写个自定义指令来统一控制会更高效。我们可以监听输入框的blur事件,手动把表单控件标记为touched,这样就能复用这个“首次blur后触发验证”的规则。

步骤1:创建自定义指令

import { Directive, HostListener, Optional, Self } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  selector: '[appBlurTriggerValidate]'
})
export class BlurTriggerValidateDirective {
  constructor(@Optional() @Self() private control: NgControl) {}

  // 监听输入框的blur事件
  @HostListener('blur')
  onInputBlur(): void {
    if (this.control?.control) {
      // 标记控件为已触碰
      this.control.control.markAsTouched();
      // 手动触发一次验证更新(可选)
      this.control.control.updateValueAndValidity({ onlySelf: true });
    }
  }
}

步骤2:在表单控件上使用指令

<input nz-input formControlName="email" appBlurTriggerValidate />
<!-- 错误提示的条件判断和方案一一样 -->
<nz-error-tip *ngIf="userForm.get('email')?.invalid && userForm.get('email')?.touched">
  请输入有效的邮箱格式
</nz-error-tip>

这样所有加了appBlurTriggerValidate指令的输入框,都会在首次blur后才触发错误提示,不用每个控件都写重复的条件。

额外小技巧:配合ng-zorro的状态控制

你还可以结合nz-form-control的nzValidateStatus属性,让控件的样式也和验证状态同步:

<nz-form-control 
  [nzValidateStatus]="userForm.get('username')?.invalid && userForm.get('username')?.touched ? 'error' : ''"
>
  <input nz-input formControlName="username" appBlurTriggerValidate />
  <nz-error-tip *ngIf="userForm.get('username')?.invalid && userForm.get('username')?.touched">
    用户名不能为空,且长度至少3位
  </nz-error-tip>
</nz-form-control>

这样不仅错误提示会在blur后显示,输入框的边框样式也会同步变成错误状态,体验更一致。

内容的提问来源于stack exchange,提问作者skwny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:22:59