Reputation: 1546
I create a regex to validate email address this is my regex:
@"^\w+(\.?[-+\w])*@\w+([-.]\w+)*\.[a-zA-Z]{2,80}$"
I would like that the max length of the mail address is 80 but with this regex i only limit the last part of the mail after the .
Now
aaa@aa.ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff is invalid
but
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@aa.ffffffff is valid
How can i do this?
Upvotes: 5
Views: 1708
Reputation: 32561
Not sure if I made an obvious mistake, but I've made a test with a conditional expression with Yes and No clause. The test condition is the email format validation:
(?:^\w+\.?[-+\w]*@\w+(?:[-.]\w+)*\.[a-zA-Z]{2,}$)
If the condition is met, search the input for any character between 6 (the minimum length - [email protected]) and 80 repetitions:
^.{6,80}$
If the condition is not met, search again for the expression in the test condition (which produces no result):
^\w+\.?[-+\w]*@\w+(?:[-.]\w+)*\.[a-zA-Z]{2,}$
The whole regex looks like this:
(?(?:^\w+\.?[-+\w]*@\w+(?:[-.]\w+)*\.[a-zA-Z]{2,}$)^.{6,80}$|^\w+\.?[-+\w]*@\w+(?:[-.]\w+)*\.[a-zA-Z]{2,}$)
And it seems it's working.
Upvotes: 1
Reputation: 5804
You can validate within two steps.Just try it out.
Regex validCharsRegex = new Regex(@"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*" +
"@" + @"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$");
Match match = validCharsRegex.Match(stringText.Trim());
if (match.Success && stringText.Length <=80 )
{
// You logic here
}
Upvotes: 1
Reputation: 913
You can check sthe String.Lenght property to validate. If you wanna check the parts before and after the " @ " character, you can do a string.Split on character @ , and check the lenght of the 2 string resulting from the operation
Upvotes: 0