heisenberg7584
heisenberg7584

Reputation: 740

Mails separated by comas - add check for mail length (JS regex)

I have a regex for emails:

const EMAIL = /[a-z0-9-_.+]+@[a-z0-9]+[a-z0-9-.]*\.[a-z0-9]{2,9}/;

And one for validating if they are separated by comas. I need it for input validation.

const COMAS = new RegExp(
  `^(?:${VALID_EMAIL.source}(?:, *)?)+$`,
  'i',
);

I wanted to add a condition that from now on the max length of the mail would be 50. I tried solutions from other SO threads, but non of them works for me. It works when there is just one mail in array, but for many it counts the length of all the strings in the array...

const VALID_EMAIL = /(?!.{51})[a-z0-9-_.+]+@[a-z0-9]+[a-z0-9-.]*\.[a-z0-9]{2,9}/;

Upvotes: 3

Views: 38

Answers (1)

anubhava
anubhava

Reputation: 785481

You may use this regex with a negated character class:

const VALID_EMAIL = /(?![^,]{51})[-a-z0-9_.+]+@[a-z0-9]+[a-z0-9-.]*\.[a-z0-9]{2,9}/;

(?!.{51}) will fail the match if there are 51 of any characters in the input while (?![^,]{51}) will fail only if there are 51 non-comma characters in an email.

Upvotes: 2

Related Questions