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

Angular中实现prefix或suffix至少选填一个的表单校验方案

Angular实现prefix/suffix至少填一个的表单验证

实现步骤

1. 编写表单组级别的自定义验证器

创建一个验证函数,用于检查表单组中的prefix和suffix控件是否至少有一个不为空值:

import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

export function atLeastOneRequiredValidator(): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const prefix = control.get('prefix')?.value;
    const suffix = control.get('suffix')?.value;
    
    // 排除仅输入空格的情况,确保实际有内容才视为有效
    const prefixEmpty = !prefix || prefix.trim() === '';
    const suffixEmpty = !suffix || suffix.trim() === '';
    
    return prefixEmpty && suffixEmpty ? { atLeastOneRequired: true } : null;
  };
}

2. 将验证器绑定到FormGroup

修改FormGroup的初始化代码,把自定义验证器加入到表单组的验证规则中:

this.configGroup = new FormGroup({
  accountOne: new FormControl(null),
  accountTwo: new FormControl(null),
  prefix: new FormControl(""),
  suffix: new FormControl(""),
  critical: new FormControl(null),
  medium: new FormControl(null),
  low: new FormControl(null),
  none: new FormControl(null)
}, { validators: atLeastOneRequiredValidator() }); // 绑定组级验证器

3. 在模板中展示错误提示

更新HTML模板,添加针对该自定义错误的提示逻辑,可放在两个输入框的下方统一提示:

<div class="cred-ref-id-wrap">
  <label for="prefix"
         [invalid]="(!configGroup?.controls?.prefix?.pristine) && (!configGroup?.controls?.prefix?.valid)">
    prefix
    <input
      [formControlName]="'prefix'" 
      [placeholder]="'release'"
      [autocomplete]="'off'"
      (focusout)="getValue('prefix')">
  </label>
</div>

<div class="cred-ref-id-wrap">
  <label for="suffix"
         [invalid]="(!configGroup?.controls?.suffix?.pristine) && (!configGroup?.controls?.suffix?.valid)">
    suffix
    <input
      [formControlName]="'suffix'" 
      [placeholder]="'suffix'"
      [autocomplete]="'off'"
      (focusout)="getValue('suffix')">
  </label>
</div>

<!-- 自定义验证错误提示 -->
<div *ngIf="configGroup.hasError('atLeastOneRequired') && (configGroup.touched || configGroup.dirty)" class="error-text">
  请至少填写prefix或suffix中的一个
</div>

4. 提交时触发完整验证

在表单提交方法中,先标记所有控件为已触碰,确保验证规则全部触发后再判断是否提交:

handleSubmit() {
  this.configGroup.markAllAsTouched();
  
  if (this.configGroup.valid) {
    // 验证通过,执行提交逻辑
    console.log('表单数据:', this.configGroup.value);
  }
}

关键说明

  • 该验证器作用于整个FormGroup,因为需要同时校验两个控件的状态,而非单个控件。
  • 使用trim()过滤空格输入,避免用户仅输入空格就通过验证的情况。
  • 通过configGroup.touched或configGroup.dirty控制错误提示时机,避免页面加载时就显示错误信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 11:30:12