0

I have a Regex email validation pattern:

/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i

My task is to adjust this pattern to comply with RFC 5321 standards, meaning not more than more than 64 characters in the local part and not more than 255 characters in the domain part. Currently, the pattern validates much longer emails.

My question is how is t possible to restrict the length of the local part (prior to @ sign) to max 64 chars, and the domain part (after the @ sign) to max 255 chars.

guitarfreak
  • 89
  • 1
  • 8
  • 2
    https://davidcel.is/posts/stop-validating-email-addresses-with-regex/ and http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html – Biffen May 03 '18 at 08:22
  • If you are making validation on the frontend, just use `` – Endless May 03 '18 at 08:23
  • Came across both resources while searching the answer to my question, not helpful. I understand the issues associated with Regex email validation, but I do not understand how to solve the problem in this specific way. – guitarfreak May 03 '18 at 08:24
  • @Endless Indeed :) But I want to solve the Regex puzzle. – guitarfreak May 03 '18 at 08:25

2 Answers2

0

If you just want to limit the number of characters matched by an expression, most regular expressions support bounds by using braces. For instance,

\d{3}-\d{3}-\d{4}

will match (US) phone numbers: exactly three digits, then a hyphen, then exactly three digits, then another hyphen, then exactly four digits.

Likewise, you can set upper or lower limits:

\d{5,10}

means "at least 5, but not more than 10 digits".

See Answer here

xNappy
  • 158
  • 1
  • 4
  • 12
  • Thanks, but this is not a solution in my case. I don't want to dictate the number of characters to be inputed. My aim is to limit the overall length of both components. I came across: ^(?=.{1,15}$)[a-zA-Z0-9]*[^$%^&*;:,<>?()\"']*$ Which works well restricting the number of characters for the entire pattern, but could not use it twice. – guitarfreak May 03 '18 at 08:28
0

Finally, after hours of struggling, I have an email pattern that verifies whether:

  • local part is not longer than 64 chars;
  • domain part (after @ sign and before the . dot) - not more than 63 chars;
  • domain part (after . dot and until the end) - not longer than 63 chars;

It is not exactly compliant with RFC's 64/255, but I am sacrificing this provision since the our back-end verifies it this way.

^([-!#-'*+\/-9=?A-Z^-~]{0,64}+(\.[-!#-'*+\/-9=?A-Z^-~]+)*|"\s([]!#-[^-~ \t]|(\\[\t -~]))+")@[0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?(\.[0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?)$ 
guitarfreak
  • 89
  • 1
  • 8