如何在Angular表单中实现排除常见邮箱域名的验证?
问题:排除常见公共邮箱域名的验证实现
我需要在项目中排除gmail.com、outlook.com这类常见公共邮箱域名,现有Angular项目的代码如下,请问如何基于这些代码实现该类型的验证?
现有代码
onboarding.component.html
<div class="w-full my-3 md:items-center"> <input class="w-full form--primary bg-white border-none h-16 tracking-wide bg--primary__lightblue" placeholder="Email" formControlName="email" id="email" maxlength="80" name="email" size="20" type="text" [class.is-invalid]="!hubspot.get('email').valid && hubspot.get('email').touched"/> <div *ngIf="hubspot.get('email').errors?.required && hubspot.get('email').touched" class="invalid-feedback"> Campo necessario. </div> <div *ngIf="hubspot.get('email').errors?.email && hubspot.get('email').touched" class="invalid-feedback"> Inserisci un email valida. </div> <br> </div>
onboarding.component.ts
@Component({ selector: 'app-onboarding', templateUrl: './onboarding.component.html', styleUrls: ['./onboarding.component.scss'] }) export class OnboardingComponent implements OnInit { field: string = ''; hubspot: FormGroup; @ViewChild('successModal') successModal: TemplateRef<any>; @ViewChild('errorModal') errorModal: TemplateRef<any>; constructor(private formBuilder: FormBuilder, private router: Router, private hubspotService: HubspotService, public dialog: MatDialog, private titleService: Title) { this.titleService.setTitle('P24: Onboarding'); } ngOnInit() { this.hubspot = this.formBuilder.group({ email: new FormControl('', [Validators.email, Validators.required]), etc... }); } onSubmit() { const body = { fields: [ { name: 'email', value: this.hubspot.controls.email.value }] } } }
解决方案
1. 编写自定义域名黑名单验证器
在组件类中添加自定义验证器函数,用于检测邮箱域名是否在黑名单内:
// 定义需要排除的公共邮箱域名列表 const blockedDomains = [ 'gmail.com', 'outlook.com', 'yahoo.com', 'hotmail.com', // 可根据需求添加更多域名 ]; // 自定义验证器 blockedEmailDomainValidator(control: AbstractControl): ValidationErrors | null { const email = control.value; if (!email) return null; // 空值由required验证器处理 // 提取并转换为小写的域名部分 const domain = email.split('@')[1]?.toLowerCase(); if (domain && blockedDomains.includes(domain)) { return { blockedDomain: true }; } return null; }
2. 将验证器添加到表单控件
修改ngOnInit中的FormControl配置,把自定义验证器加入验证器数组:
ngOnInit() { this.hubspot = this.formBuilder.group({ email: new FormControl('', [ Validators.required, Validators.email, this.blockedEmailDomainValidator // 加入自定义验证器 ]), // 其他表单控件... }); }
3. 在模板中添加对应错误提示
在现有错误提示下方,添加黑名单域名的错误提示:
<div *ngIf="hubspot.get('email').errors?.blockedDomain && hubspot.get('email').touched" class="invalid-feedback"> 请使用非公共邮箱地址。 </div>
注意事项
- 扩展
blockedDomains可添加更多需要排除的公共域名; - 使用
toLowerCase()确保域名检测不区分大小写; - 验证器仅在邮箱格式有效(通过
Validators.email验证)后才会生效,避免无效邮箱的干扰。
内容的提问来源于stack exchange,提问作者Sebastian Lillo
相关产品推荐
相关产品推荐

