heisenberg7584
heisenberg7584

Reputation: 740

Set max email length in js regex - emails validated by comas

I have a regex for emails:

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

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...

Upvotes: 0

Views: 504

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

In order to solve the problem, you really need a lookahead, but the essence here is to make sure you negate the right pattern.

If you have a closer look at your validation regex, /[a-z0-9-_.+]+@[a-z0-9]+[a-z0-9-.]*\.[a-z0-9]{2,9}/, you will notice that the email cannot have a comma inside. This means, you can use a [^,] instead of . in your negative lookahead to only apply the length limit on a single email.

So, you need to use

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

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

If you do not want to allow , and spaces at the end of string re-write the COMMAS pattern as

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

If you want to support any kind of whitespace, replace the literal space with \\s.

Upvotes: 0

Ben
Ben

Reputation: 2255

If you really want to do it through the regex, you can add a lookahead assertion like this at the beginning of the regex:

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

(?!.{51}) will make sure that it's impossible to match more than 50 characters from the start of the string, without actually consuming any of the characters in it, so they will still be available for the regex match.

It matches emails that are less than 50 characters.

enter image description here

It does not match emails that are more than 50 characters.

enter image description here

Upvotes: 2

Related Questions