tags:

views:

53

answers:

3

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.

A: 
^([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}$
+2  A: 

Why use a regexp when you can simply check the length of the string? If you must, use a second regexp:

^.{1,150}$
Aaron Digulla
A: 

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.

Rorick
Think it's better to implement this. Thought I would do this without javascript validation and alert box, since rest of the textboxes on the page have validators to show error messages. However, don't think I have a choice in this.
Mini
There's one more thing. The text box accepts comma separated email address. So return email.length <= 20 wont work. I will have to split and individually check length of each email address.
Mini
Of course, I meant single email but not content of text box as a whole. So, yes, you need to split.
Rorick
Thanks for all the help.
Mini