1

I have a regex question, there is field for email of 60 characters. I got the regex working for email validation, but I am not sure how to ignore whitespaces after the email but only upto the whole string is 60 chars. If there is anything after 60 chars then its not valid.

^([A-Za-z0-9!#$%&'*+/=?^_`{|}~-])([A-Za-z0-9.!#$%&'*+/=?^_`{|}~-])*[@]([A-Za-z0-9.\-])([A-Za-z0-9.\-])*[.][A-Za-z.]{2,6}[ \t]+$

This should be a valid string (I am using quotes here to show string length) 'test1.test123@testtesttest.com '

This should not be a valid string 'test1.test123@testtesttest.com m'

mehwish
  • 199
  • 3
  • 15

2 Answers2

0

The mentioned regex does not work (see below)

enter image description here

So I've used mine and added validation for max limit of 60 chars

^(?!^.{60})(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|([a-zA-Z0-9]+[\w-]*\.)+[a-zA-Z]{1}[a-zA-Z0-9-]{1,23})

This regex uses lookarounds syntax. You can see the output in various screenshots. You can check how it works at here.

Here (?!^.{60}) matches max limit of 60 chars. And rest of regex syntax to validate the proper email address.

enter image description here

enter image description here

If also, see that the regex does not validate the string test1.test123@testtesttest.com m.

enter image description here

user1672994
  • 10,509
  • 1
  • 19
  • 32
0

Well, if you insist on using Regex, you can use positive lookahead to limit the total length of the string by simply adding the following right before your regex:

(?=.{6,60}$)

That would restrict the total length of the input string to be between 6 (the minimum length of a valid email address) and 60 (your preferred maximum length).

You could also replace [ \t]+ with \s+ to match other whitespace characters or with \s* to accept the input if it does or does not end with whitespace characters if you're interested in matching all kinds whitespace characters.

Therefore, your pattern would look something like this:

^(?=.{6,60}$)([A-Za-z0-9!#$%&'*+/=?^_`{|}~-])([A-Za-z0-9.!#$%&'*+/=?^_`{|}~-])*[@]([A-Za-z0-9.\-])([A-Za-z0-9.\-])*[.][A-Za-z.]{2,6}\s*$

Try it online.

Hope that helps.