Search code examples
angulartypescript

How to Validate Multiple Email Addresses in a Reactive Form in Angular 4


I have a requirement for inputting 50 email address with a same domain name (gmail.com).

I am using a Reactive form. I have added some code that I have written form it is not working for me.

https://stackblitz.com/edit/angular-wfwfow

Can anyone help me on this please?

emailPattern = "[a-zA-Z0-9_.+-,;]+@(?:(?:[a-zA-Z0-9-]+\.,;)?[a-zA-Z]+\.,;)?(gmail)\.com";

 ngOnInit() {
        this.accountingForm = this.fb.group({
            'day' : [null, Validators.required], 
            'email': ['',
                Validators.compose([
                    Validators.required,Validators.pattern(this.emailPattern),this.commaSepEmail
                ])
            ]
        });
    }
    commaSepEmail = (control: AbstractControl): { [key: string]: any } | null => {
        console.log("This is value:" + control.value);
        if (!_.isEmpty(control.value)){
            var emails= control.value.split(',');
            const forbidden = emails.some((email:any) => Validators.email(new FormControl(email)));
        console.log(forbidden);
        return forbidden ? { 'email': { value: control.value.trim() } } : null;
        }
    };
 <form [formGroup]="accountingForm" (ngSubmit)="generateSOR(accountingForm.value)">
    <input formControlName="email" [pattern]="emailPattern" placeholder="Email Address">
    <button type="submit" mat-raised-button class="mat-primary" [disabled]="!accountingForm.valid">Generate</button>
    </form>


Solution

  • I believe I spotted the issue you are having with the button not being enabled. if you change your emailPattern

    from string format

    emailPattern = "[a-zA-Z0-9_.+-,;]+@(?:(?:[a-zA-Z0-9-]+\.,;)?[a-zA-Z]+\.,;)?(gmail)\.com";

    to regex format

    emailPattern = /[a-zA-Z0-9_.+-,;]+@(?:(?:[a-zA-Z0-9-]+\.,;)?[a-zA-Z]+\.,;)?(gmail)\.com/;

    I believe it will work. From what I was testing you might want to fine tune the regex to better achieve your expected results but this solves the issue with the button not being enabled.

    I usually prefer to use regex expressions when possible instead of strings. It's also more readable.