Does asp.net have a function for checking email addresses?

I noticed that if you try to send an email to an invalid address, an exception is thrown:

MailAddress To=new MailAddress("invalidemailaddress","recipientname");

throws:

 "The specified string is not in the form required for an e-mail address"

This means that .Net must be installed in MailAddress to check if the email address is valid. Is there a way to call this "validate" function directly? This way, I will not need to create my own IsValid function.

+3
source share
5 answers

, .Net-, : MailAdress ParseAddress, , , System.Net.Mime.MailBnfHelper. internal, () .

, - , . , , .

+2

, :

public bool ValidateEmailAddress (string email)
{
   if (string.IsNullOrEmpty (email)) return false;

    try
    {
        MailAddress to = new MailAddress (email);

        return true;
    }
    catch (WhateverException e)
    {
        return false;
    }
}

. , . , 100% , .NET . ( ) , . , - , , .NET. Regex, Regex ( .NET), validaton , .NET, t . , 100% .NET( , ), try/catch, , , - .

+9

CodeProject.

, :

public static bool isEmail(string inputEmail)
{
   inputEmail  = NulltoString(inputEmail);
   string strRegex = @"^([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})(\]?)$";

   Regex re = new Regex(strRegex);

   if (re.IsMatch(inputEmail))
    return (true);
   else
    return (false);
}
+1

, , .

, , , , :

0

:

class EmailAddress
{
  private MailAddress _email;

  public string Address
  {
    get
    {
      return _email == null ? string.Empty : _email.Address;
    }
  }

  public string DisplayName
  {
    get
    {
      return _email == null ? string.Empty : _email.DisplayName;
    }
  }

  public string Host
  {
    get
    {
      return _email == null ? string.Empty : _email.Host;
    }
  }

  public string User
  {
    get
    {
      return _email == null ? string.Empty : _email.User;
    }
  }

  public EmailAddress(string email)
  {
    try {
      _email = new MailAddress(email);
    }
    catch (Exception) {
      _email = null;
    }
  }

  public EmailAddress(string email, string displayName)
  {
    try {
      _email = new MailAddress(email, displayName);
    }
    catch (Exception) {
      _email = null;
    }
  }

  public EmailAddress(string email, string displayName, Encoding displayNameEncoding)
  {
    try {
      _email = new MailAddress(email, displayName, displayNameEncoding);
    }
    catch (Exception) {
      _email = null;
    }
  }

  public bool IsValid()
  {
    return _email == null ? false : true;
  }

  public override string ToString()
  {
    return this.Address;
  }
}

MailAddress, , . IsValid:

var email = new EmailAddress("user@host.com");
if (email.IsValid()) {
  ...
}
else {
  ...
}
0

Source: https://habr.com/ru/post/1724160/


All Articles