2

I have an issue in validating multiple comma separated email address to one recipient field. I have no issue in validating one email. Any pointers are much appreciated. My code is below thanks.

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>

Typescript

ngOnInit() {

this.sendEmailForm = this.fb.group({
  toAddress: new FormControl('', [Validators.email, Validators.required])        

});

}

Will I have to write any custom validator?

DJ4186
  • 159
  • 1
  • 3
  • 16

1 Answers1

12

You could create custom validator which calls Validators.email for each email in input value - 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;
  };

and use it like

this.sendEmailForm = this.fb.group({
      'toAddress': ['', [Validators.required, this.commaSepEmail]]
});
Hikmat G.
  • 2,591
  • 1
  • 20
  • 40
  • 2
    This is great, however I'd recommend changing to `control.value.split(',').map(e=>e.trim());` for the ex: `e@a.com, f@b.com` (note space after comma) – rynop Feb 07 '19 at 17:22
  • 1
    Noticed that default validator also validates dd@c This isnt correct. – Mukus Jan 10 '20 at 23:04