ps-team
10/27/2017 - 9:34 AM

A re-usable C# function for backend email validation. No need to use long REGEX which, depending on the expression, may not capture all poss

A re-usable C# function for backend email validation. No need to use long REGEX which, depending on the expression, may not capture all possibilities. The .Net MailAddress class does all this for us, so by sending it a string with an invalid email format, it will error which we can capture and use to dictate what to do next.

@using System.Net.Mail

@{
  string email = "joe.bloggs@eggy.com";

  if(IsValidEmail(email))
  {
    // do something like submit the form and store the data, send an email or w/e
  }
  else
  {
    // do something like print an error message
  }
}


@functions
{
  // FUNCTION : check if email address is valid
  public bool IsValidEmail(string email)
  {
    try
    {
      var mail = new MailAddress(email);
      return true;
    }
    catch
    {
      return false;
    }
  }
}