2

I have this method to validate email addresses:

public static bool isEmail(string inputEmail)
{
    inputEmail = NulltoString(inputEmail);
    string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                      @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                      @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
    Regex re = new Regex(strRegex);
    if (re.IsMatch(inputEmail))
        return (true);
    else
        return (false);
}

But I get the error: The name 'NulltoString' does not exist in the current context.

Is there a string method that is equivalent to NulltoString()?

forsvarir
  • 10,499
  • 6
  • 42
  • 75
Soatl
  • 9,924
  • 28
  • 91
  • 149
  • 3
    There is no such thing as NulltoString. What did you expect? – John Cromartie May 18 '11 at 19:04
  • 4
    Your method is wrong. http://stackoverflow.com/questions/1903356/email-validation-regular-expression/1903368#1903368 – SLaks May 18 '11 at 19:05
  • At the very least, you shouldn't parse the regex every time you call the method. – SLaks May 18 '11 at 19:06
  • 1
    @John Cromartie - Why do you think I asked the question? – Soatl May 18 '11 at 19:10
  • @SsRide360 - I think John was wondering why you would ask for an equivalent to something called `NulltoString` without explaining what `NulltoString` is or how you would expect it to behave if it did exist. – Joel Mueller May 18 '11 at 21:40
  • Ahh. I just saw a method with `NulltoString` in it so I assumed that it was some really really old deprecated method. – Soatl May 19 '11 at 13:38

4 Answers4

7

The C# language already has a good feature for this, the null-coalescing operator:

inputEmail = inputEmail ?? string.Empty;
Steven
  • 159,023
  • 23
  • 313
  • 420
2

Try using the following:

inputEmail = inputEmail ?? String.Empty;

Mr47
  • 2,626
  • 1
  • 18
  • 25
0

I suggest

 public static bool isEmail(string inputEmail)
{
    inputEmail = inputEmail?? string.Empty;
    string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
          @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
          @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
    Regex re = new Regex(strRegex);
    if (re.IsMatch(inputEmail))
        return (true);
    else
        return (false);
}

More efficient than that:

     if (null == inputEmail)
         return false;
sehe
  • 350,152
  • 45
  • 431
  • 590
0

You could try

if(string.IsNullOrEmpty(inputEmail))
    //throw exception
Xaisoft
  • 44,403
  • 86
  • 275
  • 425