Email address regular expression with max length

html, regex

Solution

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.

Problem

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.

Original source