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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With