0

I am working on email validations using regular expressions, where I need some fixed email values to validate before proceeding

Here is a clear requirement

User can only have up to 50 character before the Octets (@) and a maximum of 25 characters after the Octets, with a total of 80 characters

I used normal regex to validate email like

let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

And now for the above requirement I am trying to create an expression like

let reg = /^\w+([\.-]?(\w{2,50})+)*@(\w{2,25})+([\.-]?\w+)*(\.\w{2,3})+$/;

But it's taking only starting character(not accepting lower than two) and not the last number of requirement, So any help would be appreciated.

Kirankumar Dafda
  • 2,354
  • 5
  • 29
  • 56

1 Answers1

1

If you want to match 1-50 word chars before the @ (so no . or -) and 1-25 word chars after the @ (also no . or -) and a total of no more than 80 chars:

^(?!.{81})(?:\w+[.-])*\w{1,50}@\w{1,25}(?:[.-]\w+)*\.\w{2,3}$

Explanation

  • ^ Start of string
  • (?!.{81}) Negative lookahead, assert that from the current position there are not 81 chars directly to the right
  • (?:\w+[.-])* Repeat 0+ times 1+ word chars and either a . or -
  • \w{1,50} Match 1-50 word chars
  • @ Match literally
  • \w{1,25} Match 1-25 word chars
  • (?:[.-]\w+)* Repeat 0+ times matching either a . or - and 1+ word chars
  • \.\w{2,3} Match a . and 2-3 word chars
  • $ End of string

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • 1
    a little bit optimized your solution ```^(?!.{81})[\w.-]{1,50}@[\w.-]{1,25}\.[a-z]{2,24}$``` check online [here](https://regex101.com/r/y5hy2G/1) according to [this](https://stackoverflow.com/questions/9238640/how-long-can-a-tld-possibly-be) information, last part of domain name is currently 24 characters max – Konstantin Mezentsev Sep 22 '20 at 02:41
  • 1
    Thank you so much for this quick response. – Kirankumar Dafda Sep 22 '20 at 05:03