Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Email address regular expression with max length

Tags:

html

regex

I have a regular expression that I am using for client side HTML5 validation and I need to add a max length element to it. Here is my regular expression :

@pattern = @"^([a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)$"

How would I for example limit it to 50 characters?

EDIT : I need to check the max length in the same regular expression as I am using HTML5 validation which only currently allows checking against required and pattern attributes.

like image 277
user517406 Avatar asked Dec 21 '22 07:12

user517406


1 Answers

If you absolutely must use a regex, add a lookahead assertion at the start of the regex:

@pattern = @"^(?!.{51})([a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)$"

The (?!.{51}) asserts that it's impossible to match 51 characters starting from the beginning of the string, without actually consuming any of the characters, so they are still available for the actual regex match.

like image 145
Tim Pietzcker Avatar answered Dec 28 '22 23:12

Tim Pietzcker