我在验证多个逗号分隔的电子邮件地址到一个收件人字段时遇到问题。验证一封电子邮件没有任何问题。非常感谢任何指针。我的代码在下面谢谢。
html
<form ng-submit="onSend()" [formGroup]="sendEmailForm">
<div class="email-field">
<mat-form-field>
<input matInput #emailTo placeholder="to@company.ca, to@company.ca..." formControlName="toAddress">
</mat-form-field>
</form>
打字稿
ngOnInit() {
this.sendEmailForm = this.fb.group({
toAddress: new FormControl('', [Validators.email, Validators.required])
});
}
我必须写任何自定义验证器吗?
答案 0 :(得分:3)
您可以创建自定义验证程序,该验证程序针对输入值中的每封电子邮件调用Validators.email
-stackblitz
commaSepEmail = (control: AbstractControl): { [key: string]: any } | null => {
const emails = control.value.split(',').map(e=>e.trim());
const forbidden = emails.some(email => Validators.email(new FormControl(email)));
return forbidden ? { 'toAddress': { value: control.value } } : null;
};
并像
一样使用它this.sendEmailForm = this.fb.group({
'toAddress': ['', [Validators.required, this.commaSepEmail]]
});