This is a simple C# .NET Program to validate email address. The ValildateEmail() function checks for a valid email and returns true if the email address is a valid email otherwise it returns false if the email address is not proper syntax. The code is well commented and should explain what is happening .
This code uses regular expressions to validate the structure of the email address and checks for the presence of “@” and “.” characters. Additionally, it has a separate function ContainsIllegalCharacters
to check for the presence of any illegal characters in the email address.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | using System; using System.Text.RegularExpressions; class Program { static void Main() { bool isValid = ValidateEmail(email); if (isValid) { Console.WriteLine("Email is valid."); } else { Console.WriteLine("Email is invalid."); } } static bool ValidateEmail(string email) { // Define the regular expression pattern for a valid email address string pattern = @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"; // Check if the email matches the pattern if (Regex.IsMatch(email, pattern)) { // Check for illegal characters if (ContainsIllegalCharacters(email)) { return false; } return true; } return false; } static bool ContainsIllegalCharacters(string input) { // Define a pattern for acceptable characters in the email string acceptablePattern = @"^[a-zA-Z0-9._%+-@]+$"; // Check if the input contains any illegal characters return !Regex.IsMatch(input, acceptablePattern); } } |