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

Angular Material带邮件验证的Chips组件:错误提示问题求助

解决Angular Chips邮箱输入框的错误提示问题

针对Chips输入框无效邮箱和必填项错误提示的问题,可通过以下调整修复:

1. 完善自定义验证器,返回具体错误信息

修改验证器,标记无效邮箱的同时返回具体列表,让提示更精准:

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

const REGEXP_EMAIL =
  /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i;

export const emailsArrayValidator = (control: FormControl) => {
  const emails: string[] = Array.isArray(control.value) ? control.value : [];
  // 过滤空内容和无效邮箱
  const invalidEmails = emails.filter(email => {
    const trimmedEmail = email.trim();
    return trimmedEmail === '' || !REGEXP_EMAIL.test(trimmedEmail);
  });
  
  if (invalidEmails.length > 0) {
    return { 
      invalidEmails: true,
      invalidList: invalidEmails // 返回无效邮箱列表
    };
  }
  // 处理空数组的必填验证
  return emails.length === 0 ? { required: true } : null;
};

2. 同步表单控件状态,自动触发验证

修改组件逻辑,确保添加/删除邮箱时更新表单状态,同时处理控件触摸状态:

constructor(private fb: FormBuilder) {
  this.inviteForm = this.fb.group({
    name: ['', Validators.required],
    email: ['', [Validators.required, Validators.pattern(REGEXP_EMAIL)]],
    date: ['', Validators.required],
    // 移除重复的required,自定义验证器已处理空数组
    friends: [[], [Validators.minLength(1), emailsArrayValidator]],
  });
}

// 标记控件为触摸状态并更新验证
markFriendsAsTouched() {
  this.friends.markAsTouched();
  this.friends.updateValueAndValidity();
}

addFriend(event: MatChipInputEvent) {
  const friendEmail = event.value.trim();
  if (!friendEmail) {
    event.chipInput!.clear();
    this.markFriendsAsTouched();
    return;
  }

  const friends = [...this.friends.value, friendEmail];
  this.friends.setValue(friends);
  // 触发验证更新错误状态
  this.friends.updateValueAndValidity();
  
  event.chipInput!.clear();
}

removeFriend(email: string) {
  const friends = this.friends.value.slice();
  const index = friends.indexOf(email);
  if (index !== -1) {
    friends.splice(index, 1);
    this.friends.setValue(friends);
    // 删除后重新验证
    this.friends.updateValueAndValidity();
  }
}

3. 优化HTML模板的错误提示逻辑

修改模板,根据错误类型显示对应提示,同时在输入框失焦时标记控件为触摸:

<mat-form-field>
  <mat-label>Enter invitation email</mat-label>
  <mat-chip-grid #chipGrid>
    @for (friend of friends.value; track friend) {
      <mat-chip-row (removed)="removeFriend(friend)" [editable]="true">
        {{ friend }}
        <button matChipRemove>
          <mat-icon>cancel</mat-icon>
        </button>
      </mat-chip-row>
    }
    <input
      [matChipInputFor]="chipGrid"
      [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
      [matChipInputAddOnBlur]="addOnBlur"
      (matChipInputTokenEnd)="addFriend($event)"
      (blur)="markFriendsAsTouched()" <!-- 失焦时标记控件为触摸 -->
    />
  </mat-chip-grid>
  
  @if (friends.hasError('required') && friends.touched) {
    <mat-error>请至少添加一个邮箱</mat-error>
  }
  @if (friends.hasError('invalidEmails') && friends.touched) {
    <mat-error>存在无效邮箱:{{ friends.getError('invalidList').join(', ') }}</mat-error>
  }
</mat-form-field>

关键调整说明

  • 控件状态同步:通过markAsTouched()和updateValueAndValidity()确保表单错误状态实时更新,解决touched状态不触发的问题。
  • 验证器增强:返回无效邮箱列表,让错误提示更具体;同时在验证器内处理空数组情况,与Angular表单错误体系对齐。
  • 错误提示拆分:根据不同错误类型(必填、无效邮箱)显示对应提示,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 10:55:25