C# Function Check Email Syntax C# Code Library

We need a C# function that allows us to know if the entered email has a correct syntax. This C# function will be good for us to have it to incorporate into our projects. Normally it is used to verify the email before saving it in a database or using it to send emails.



Strategy to follow to develop the C# Function Check Email Syntax

  1. Create a C# Function that returns us if the e-mail entered is correct.

1. Creating the C# Function Check Email Syntax

Create a public C# Function called "VerifyEmailSyntax"

public static bool VerifyEmailSyntax(string email)
{
    try
    {
        string pattern =
        @"^([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})(\]?)$";

        if ((Regex.IsMatch(email, pattern)))
            return true;
        else
            return false;
        }
    catch (Exception)
    {
       return false;
    }
}


Running the C# Function Check Email Syntax

Below is the C# program Running the C# Function Check Email Syntax

using System;
using System.Text.RegularExpressions;

namespace VerifyEmailSyntax
{

    internal class Program
    {
        public static bool VerifyEmailSyntax(string email)
        {
            try
            {
                string pattern =
                @"^([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})(\]?)$";

                if ((Regex.IsMatch(email, pattern)))
                    return true;
                else
                    return false;
            }
            catch (Exception)
            {
                return false;
            }
        }

        static void Main(string[] args)
        {
            bool debug = true;
            string text;           

            Console.WriteLine("Enter Email:");
            text = Console.ReadLine();
           
            if (VerifyEmailSyntax(text))           
                Console.WriteLine("Correct Email");          
            else           
                Console.WriteLine("Wrong Email");
           
            if (debug)
                Console.ReadLine();

        }
       
    }
}

Output 1

Output 2




Juan A. Ripoll - Programming Tutorials and Courses © 2024 All rights reserved.  Legal Conditions.