0

I use this regex for my email validation

/.+@.+\..+/i

I can't get it to work on my server side though. I tried this so far

var pattern = @"^.+@.+\..+i$";
var pattern = @".+@.+\..+i";

I get 0 results trying it (also in my code). Any ideas? Not sure if it helps but the requirement is to allow a@b.c so 1 char, one @ and at least one '.'.

Dejan.S
  • 18,571
  • 22
  • 69
  • 112

3 Answers3

1

The problem looks to be the i; you don't mean "ends with i" (which is i$), etc - in the javascript, the trailing .../i means "case insensitive" - but there is nothing there to be case sensitive, so just remove the i (from both would be fine, but from the C# at least). You should also remove the ^ and $ that you added from nowhere. For completeness, RegexOptions.IgnoreCase is how you ignore case in .NET Regex.

var pattern = @".+@.+\..+";
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • I'll try that out. Would you recommend the `^` and `$` in C#? Actually not sure what it does? – Dejan.S Aug 22 '14 at 07:21
  • @Dejan.S yes; they mean "start" and "end"; they aren't in the javascript version, so the javascript version matches "*has* this pattern"; with the `^`/`$`, this becomes "*is* this pattern". – Marc Gravell Aug 22 '14 at 07:22
  • @Dejan.S I need to be careful how I say this, but: if you weren't sure what they did, why did you add them? rather than, say, doing a 2 second google search to *find out* what they did? – Marc Gravell Aug 22 '14 at 07:24
  • I have no knowledge when it comes to regex. I mean I used it before like got done of the net. Now always seen the `^` `$`, but the validation before it didn't use it so I just wanted to check. Reason I ask here instead of google is that other can take knowledge from it. Because let's be honest asking this question I did is rookie :) – Dejan.S Aug 22 '14 at 07:31
  • @MarcGravell while doing validations, it's better to add start and end anchors. – Avinash Raj Aug 22 '14 at 07:32
  • @AvinashRaj that depends entirely on what you are validating, and what the validation rules are; "better" is an entirely meaningless phrase without the import context of "better at X". – Marc Gravell Aug 22 '14 at 07:33
1

Just remove the i character from the regex and then add start, end anchors to your pattern,

@"^.+@.+\..+$";

DEMO

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

JavaScript:

function validateEmail(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}

C#:

bool validateEmail(string email) 
{ 
    var re = new Regex(@"^(([^<>()\[\]\.,;:\s@""]+(\.[^<>()\[\]\.,;:\s@""]+)*)|("".+""))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$") ;
    return re.IsMatch(email);
}

see here :Validate email address in JavaScript?

Community
  • 1
  • 1
Tim.Tang
  • 3,158
  • 1
  • 15
  • 18