Problem to detect issue of Email address

Category: c# general

Question

HuaMin Chen on Mon, 22 Jan 2018 06:53:46


Hi,
Using following codes, I cannot detect problem to Email address. Why?

        bool IsValidEmail(string email)
        {
            try
            {
                var addr = new System.Net.Mail.MailAddress(email);
                return addr.Address == email;
            }
            catch
            {
                return false;
            }
        }
        protected void email_post_change(object sender, EventArgs e)
        {
            string email0 = tb_email.Text;
            if (!IsValidEmail(email0))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "ShowMessage('电子邮件地址格式有问题。')", true);
                tb_email.Focus();
                return;
            }
        }
		...


Many Thanks & Best Regards, Hua Min

Replies

Ehsan Sajjad on Mon, 22 Jan 2018 08:42:46


Can you please elaborate more, what you actually mean by not working, is the method not returning expected result.

By the way there are more better ways to validate an email address which is availble at Microsoft docs here:

How to: Verify that Strings Are in Valid Email Format

Hope it helps.

RJP1973 on Mon, 22 Jan 2018 10:31:35


You shouldn't be using the MailAddress class for validating email addresses (plus, using exceptions for validation in that way isn't a great idea).

Ehsan's post above has a link with a better way to validate an email address.

HuaMin Chen on Mon, 22 Jan 2018 15:32:42


Thanks to all.

I put IsValidEmail event to my project but then I've got these

Error	8	The name 'Regex' does not exist in the current context	C:\App6\Prog0.cs	64	25	Own_rec
Error	9	'Own_rec._Default' does not contain a definition for 'DomainMapper' and no extension method 'DomainMapper' accepting a first argument of type 'Own_rec._Default' could be found (are you missing a using directive or an assembly reference?)	C:\App6\Prog0.cs	64	64	Own_rec
Error	10	The name 'RegexOptions' does not exist in the current context	C:\App6\Prog0.cs	65	39	Own_rec


What to adjust?

Castorix31 on Mon, 22 Jan 2018 15:50:24


I put IsValidEmail event to my project but then I've got these

Error	8	The name 'Regex' does not exist in the current context	C:\App6\Prog0.cs	64	25	Own_rec
Error	9	'Own_rec._Default' does not contain a definition for 'DomainMapper' and no extension method 'DomainMapper' accepting a first argument of type 'Own_rec._Default' could be found (are you missing a using directive or an assembly reference?)	C:\App6\Prog0.cs	64	64	Own_rec
Error	10	The name 'RegexOptions' does not exist in the current context	C:\App6\Prog0.cs	65	39	Own_rec

What to adjust?

Have you added :

using System.Text.RegularExpressions;
using System.Globalization;
at beginning ?

HuaMin Chen on Tue, 23 Jan 2018 02:55:36


Many thanks.

What should be DomainMapper, due to this error?

Error	8	'Own_rec._Default' does not contain a definition for 'DomainMapper' and no extension method 'DomainMapper' accepting a first argument of type 'Own_rec._Default' could be found (are you missing a using directive or an assembly reference?)	C:\App6\Prog0.cs	65	64	Own_rec

Castorix31 on Tue, 23 Jan 2018 03:33:37


What should be DomainMapper, due to this error?

Error	8	'Own_rec._Default' does not contain a definition for 'DomainMapper' and no extension method 'DomainMapper' accepting a first argument of type 'Own_rec._Default' could be found (are you missing a using directive or an assembly reference?)	C:\App6\Prog0.cs	65	64	Own_rec

Have you added the functions inside a class ?

Like :

public partial class Form1 : Form
{
    bool invalid = false;
    private string DomainMapper(Match match)
    {
        // IdnMapping class with default property values.
        IdnMapping idn = new IdnMapping();

        string domainName = match.Groups[2].Value;
        try
        {
            domainName = idn.GetAscii(domainName);
        }
        catch (ArgumentException)
        {
            invalid = true;
        }
        return match.Groups[1].Value + domainName;
    }
    public bool IsValidEmail(string strIn)
    {
        invalid = false;
        if (String.IsNullOrEmpty(strIn))
            return false;

        // Use IdnMapping class to convert Unicode domain names.
        try
        {
            strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper, RegexOptions.None, TimeSpan.FromMilliseconds(200));
        }
        catch (RegexMatchTimeoutException)
        {
            return false;
        }

        if (invalid)
            return false;

        // Return true if strIn is in valid e-mail format.
        try
        {
            return Regex.IsMatch(strIn,
                  @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                  @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
                  RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
        }
        catch (RegexMatchTimeoutException)
        {
            return false;
        }
    }
    
    public Form1()
    {
        InitializeComponent();
    }    
    // code ...    
}