Created
October 27, 2017 09:34
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @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