2

I have a requirement to enter only 50 email address to the text box. I am using a regex expression to validate the email addresses as I have to restrict the domain name also. All I am now stuck is I am unable to write a validation to restrict the entries up to 50 email addresses.

emailPattern = /^\w+([-+.']\w+)*@abc.com(, ?\w+([-+.']\w+)*@abc.com)*$/;

Please refer my code in the below link.

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

Matze
  • 5,100
  • 6
  • 46
  • 69
Shraddha
  • 113
  • 2
  • 11
  • 2
    Replace `*$` with `{0,49}$` – Wiktor Stribiżew Oct 11 '18 at 12:19
  • Hi @WiktorStribiżew, Thank you very much for the solution. It worked for me. – Shraddha Oct 12 '18 at 09:41
  • @Shraddha/@Wiktor Stribiżew : Referring your regex , i am trying to achieve the same but accepting different domain emails and limit the emails upto 5 but it gives me performance issue. Please refer https://stackblitz.com/edit/angular-nbkp9h and below is the regex. /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})(, ?\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})){0,4}$/ – Vanu Jun 07 '21 at 09:36
  • @HV712 https://stackblitz.com/edit/multiple-email-validation check this – Shraddha Jun 08 '21 at 13:07

2 Answers2

5

There is an email validator in the @angular/forms.

You can get the regex from the email validators source :

const EMAIL_REGEXP =
    /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;

Or simply use it to create a custom validator for multiple emails :

function validateEmails(emails: string) {
  return (emails.split(',')
    .map(email => Validators.email(<AbstractControl>{ value: email }))
    .find(_ => _ !== null) === undefined);
}

function emailsValidator(control: AbstractControl): ValidationErrors | null {
  if (control.value === '' || !control.value || validateEmails(control.value)) {
    return null
  }
  return { emails: true };
}

Then use the custom validator :

this.sendEmailForm = this.fb.group({
   'toAddress': ['', emailsValidator]
});

Here is a fork of your code with the suggestion solution.

ibenjelloun
  • 7,425
  • 2
  • 29
  • 53
0

Email addresses can only contain alphanumeric characters plus special symbols !#$%’*+-/=?^_`{|}~. Note that commas are not valid address parts.

As such, the simplest way to go would be to simply split the string on commas, then evaluate each address. You can simultaneously limit or trim the number of addresses. It looks like your code is already splitting on commas, so once you've done so you can just do something like:

if(emailList.length > 50) 
   /* display an error or truncate the list */
else 
   /* iterate over the list and test each address */
Paul
  • 35,689
  • 11
  • 93
  • 122
  • Your first paragraph is incorrect in that the following is a valid email address `"fancy,v1"@example.com`, note the " characters – JGNI Oct 11 '18 at 13:04