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,749
  • 6
  • 46
  • 77
Soatl
  • 10,224
  • 28
  • 95
  • 153
  • 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
  • 166,672
  • 24
  • 332
  • 435
2

Try using the following:

inputEmail = inputEmail ?? String.Empty;

Mr47
  • 2,655
  • 1
  • 19
  • 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
  • 374,641
  • 47
  • 450
  • 633
0

You could try

if(string.IsNullOrEmpty(inputEmail))
    //throw exception
Xaisoft
  • 45,655
  • 87
  • 279
  • 432