1

I'm using the following regex to validate an email address text box in javascript:-

var regex = /^[\_]*([a-z0-9]+(\.|\_*)?)+@([a-z][a-z0-9\-]+(\.|\-*\.))+[a-z]{2,6}$/i;

I need to also run it in the back end of the asp.NET(4) VB site to prevent injection.

When I convert it to what I think it should be for .NET and run it in http://myregextester.com/ set to use .NET and VB it passes:-

^[_]*([a-z0-9]+(.|_*)?)+@([a-z][a-z0-9\-]+(.|-*.))+[a-z]{2,6}$

However when I put it in my code it doesn't work:-

If (Not Regex.IsMatch(theEmail, "^[_]*([a-z0-9]+(.|_*)?)+@([a-z][a-z0-9\-]+(.|-*.))+[a-z]{2,6}$")) Then                    
    Return False
Else
    Return True
End If

Any help with the conversion to VB would be appreciated.

2 Answers 2

2

Replace \- to -

^[_]*([a-z0-9]+(.|_*)?)+@([a-z][a-z0-9-]+(.|-*.))+[a-z]{2,6}$

And also set RegexOptions.IgnoreCase. Since /i is set.

Here i indicates IgnoreCase.

Your code will be

If (Not Regex.IsMatch(theEmail, "^[_]*([a-z0-9]+(.|_*)?)+@([a-z][a-z0-9-]+(.|-*.))+[a-z]{2,6}$", RegexOptions.IgnoreCase)) Then                    
    Return False
Else
    Return True
End If
Sign up to request clarification or add additional context in comments.

1 Comment

Unescaping - won't make a difference. Adding an ignore case option is good. As it is now, your regex matches somebody@A-B@@google.
1

It seems the only difference between the regexes is that the original one uses a literal dot \. whereas the second one uses a dot . metacharacter. The metacharacter will match anything, the literal dot will just match a dot character.

Try puting the escape back on the dot.

Your two regexes,

old

 ^ [\_]* 
 (
      [a-z0-9]+ 
      ( \. | \_* )?
 )+
 @
 (
      [a-z] [a-z0-9\-]+ 
      ( \. | \-*\. )
 )+
 [a-z]{2,6} $

new

 ^ [_]* 
 (
      [a-z0-9]+ 
      ( . | _* )?
 )+
 @
 (
      [a-z] [a-z0-9\-]+ 
      ( . | -*. )
 )+
 [a-z]{2,6} $ 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.