Skip to content

Instantly share code, notes, and snippets.

@ps-team
Created October 27, 2017 09:34
Show Gist options
  • Save ps-team/f64a1424145f527063e47547e3564f7d to your computer and use it in GitHub Desktop.
Save ps-team/f64a1424145f527063e47547e3564f7d to your computer and use it in GitHub Desktop.
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 = "[email protected]";
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;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment