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

Angular表单手机号与邮箱唯一性校验实现方案问询

实现重复手机号/邮箱检测提示的方案

步骤1:修改组件TS代码

先通过@Input接收父组件传来的已有联系人列表,再添加重复检测逻辑,最后在输入或保存时触发验证:

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-formulario',
  templateUrl: './formulario.component.html',
  styleUrls: ['./formulario.component.css']
})
export class FormularioComponent {

  @Input() contactosExistentes: Contacto[] = []; // 接收已有联系人数据
  @Output() contactoEmitido: EventEmitter<Contacto> = new EventEmitter();
  nuevoContacto: Contacto = { nombre: "", telefono: 0, email: "" };
  telefonoError: string = '';
  emailError: string = '';

  constructor() {}

  // 实时验证手机号
  verificarTelefono() {
    this.telefonoError = '';
    const telefonoExistente = this.contactosExistentes.find(
      contacto => contacto.telefono === this.nuevoContacto.telefono
    );
    if (telefonoExistente) {
      this.telefonoError = '该手机号已存在';
    }
  }

  // 实时验证邮箱
  verificarEmail() {
    this.emailError = '';
    const emailExistente = this.contactosExistentes.find(
      contacto => contacto.email.toLowerCase() === this.nuevoContacto.email.toLowerCase()
    );
    if (emailExistente) {
      this.emailError = '该邮箱已存在';
    }
  }

  recogerDatosForm() {
    // 提交前二次验证
    this.verificarTelefono();
    this.verificarEmail();
    
    if (!this.telefonoError && !this.emailError) {
      this.contactoEmitido.emit({...this.nuevoContacto}); // 传副本避免引用问题
      this.nuevoContacto = { nombre: "", telefono: 0, email: "" };
      this.telefonoError = '';
      this.emailError = '';
    } else {
      alert('存在重复的手机号或邮箱,请检查');
    }
  }
}

步骤2:修改HTML模板

绑定实时验证事件,添加错误提示显示:

<div class="form">
  <label for="nombre">Nombre</label>
  <input type="text" id="nombre" [(ngModel)]="nuevoContacto.nombre">

  <label for="telefono">Telefono</label>
  <input 
    type="text" 
    id="telefono" 
    [(ngModel)]="nuevoContacto.telefono"
    (blur)="verificarTelefono()"
    (input)="verificarTelefono()"
  >
  <!-- 手机号错误提示 -->
  <span class="error-text" *ngIf="telefonoError">{{ telefonoError }}</span>

  <label for="email">Email</label>
  <input 
    type="email" 
    id="email" 
    [(ngModel)]="nuevoContacto.email"
    (blur)="verificarEmail()"
    (input)="verificarEmail()"
  >
  <!-- 邮箱错误提示 -->
  <span class="error-text" *ngIf="emailError">{{ emailError }}</span>

  <button (click)="recogerDatosForm()">Guardar</button>
</div>

步骤3:添加错误提示样式(可选)

在CSS文件中添加错误文本样式:

.error-text {
  color: red;
  font-size: 0.8rem;
  display: block;
  margin-top: 4px;
}

说明

  1. 依赖父组件通过@Input传入已有联系人列表,才能完成重复检测
  2. 支持实时验证:用户输入或离开输入框时立即检测并显示错误
  3. 提交表单时会二次验证,确保无重复数据才会提交
  4. 提示方式可替换为Angular Material的MatSnackBar(需自行导入注入),根据项目需求选择即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 15:30:49