Reputation: 157
We have a textbox which accepts comma separated email address. The regular expression is
^(\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\s*[,]?\b)*$.
However now I am unable to add a length validation to this expression. Each email address should not be more than 150 characters. I have tried
^((\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)){1,150}\s*[,]?\b)*$.
But it doesn't work. Can you please modify the regex so that it also implements this validation too.
Upvotes: 3
Views: 13114
Reputation: 938
I arrived here looking for a way to extend my ng-pattern
for e-mail for an Angular form.
Taking Rorick's approach of checking for length separately, I found a much easier solution: just set ng-maxlength="150"
in the input. Then you can customize an error message that tells the user that the e-mail is too long.
maxlength="150"
works fine too, preventing any extra characters from being added to the field, but I liked that ng-maxlength
tells you what's wrong rather than truncating your string.
Upvotes: 0
Reputation: 328770
Why use a regexp when you can simply check the length of the string? If you must, use a second regexp:
^.{1,150}$
Upvotes: 5
Reputation: 8953
I would rather not complicate this regex further and add explicit length check before checking that e-mail matches. In JavaScript it will be something like the following:
function validateEmail(email) {
var regex = /^(\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\s*[,]?\b)*$/;
// 20 is used instead of 150 for sake of example
return email.length <= 20 && regex.test(email);
}
// validateEmail("[email protected]") == true
// validateEmail("[email protected]") == false
By the way, dot after $
in your regex seems to be a mistake, so I skipped it in my snippet.
Upvotes: 1
Reputation: 11876
^([a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]){0,70}$
Upvotes: 0