0

The below email is not valid format

fulya_42_@hotmail.coö

But all validations i found and tried so far with c# said it is correct email which is not

How can i validate email is valid or not with c# 4.5.2? thank you

Ok updated question

The reason i am asking is one of the biggest email service mandrill api throws internal server error when you try to email this address

So they must be using some kind of validation before even trying to send out email. My aim is finding what are they using to eliminate such emails before try thank you

Furkan Gözükara
  • 22,964
  • 77
  • 205
  • 342
  • 5
    _The below email is not valid format_ What makes you say that? Seems a valid address to me. `coö` is not currently using but there will be no guaranteed that it _can't_ be used in future as well. – Soner Gönül May 26 '15 at 10:46
  • 3
    Isn't it a valid email address? Non-ASCII characters are allowed in the domain part to cater for internationalized domain names. As far as I'm aware, `coö` isn't a currently used TLD, but C# can't know that it won't ever be used as one. – Mourndark May 26 '15 at 10:47
  • 3
    If you want to check against a list of TLDs, ICANN provide: https://data.iana.org/TLD/tlds-alpha-by-domain.txt – Mourndark May 26 '15 at 10:51
  • 2
    The only reliable way to validate an email is by sending a validation link to that email. Taking your example, the format is 100% correct, but the ".coö" doesn't exist (yet), so it would end up nowhere. But if anyone mistypes the first part of the address (e.g. fulua_42_@hotmail.com) it might also lead nowhere with absolutely no other way to check it than send a validation e-mail... – Laurent S. May 26 '15 at 10:53
  • @SonerGönül i say invalid because mandril api throws 500 internal error. which means they dont see it as a valid not even trying – Furkan Gözükara May 26 '15 at 11:13
  • @Mourndark that is what i am asking a solution that would work at least with current standards :) – Furkan Gözükara May 26 '15 at 11:14
  • @Bartdude if it is 100% correct why mandrill api throws internal error? one of the biggest commercial emailing service? not even trying to send it? – Furkan Gözükara May 26 '15 at 11:26
  • @MonsterMMORPG I believe all the methods you can do in C# *do* conform to the current standards. If you want to catch the fact that the TLD in your example has never actually used (to date), you're going to have to add in some sort of code to check the ICANN list of TLDs I posted. – Mourndark May 26 '15 at 11:47
  • Probably because mandrill not only checks formatting but also has a whitelist of existing domain names, which has nothing to do with formatting. – Laurent S. May 26 '15 at 11:50
  • @Bartdude are there any way to get any decent whitelist of existing domains? – Furkan Gözükara May 26 '15 at 12:11
  • ok is this valid email or not : pokemonozcan-24@hotmail.com – Furkan Gözükara May 26 '15 at 12:34
  • @Bartdude mandrill just also ignored this : pokemonozcan-24@hotmail.com – Furkan Gözükara May 26 '15 at 12:34
  • well as you can see there's nothing special about this address so you might need to get some more info on mandrill's rules... – Laurent S. May 26 '15 at 16:32
  • Possible duplicate of [C# code to validate email address](http://stackoverflow.com/questions/1365407/c-sharp-code-to-validate-email-address) – WonderWorker Mar 15 '16 at 14:39
  • It's really easy to check for a validity of the address and the domain without using regexes. -- See my answer for details. – BrainSlugs83 Jun 22 '17 at 21:57

4 Answers4

0

By using Regex

string emailID = "fulya_42_@hotmail.coö";

        bool isEmail = Regex.IsMatch(emailID, @"\A(?:[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)\Z");

        if (isEmail)
        {
            Response.Write("Valid");
        }
Satinder singh
  • 10,100
  • 16
  • 60
  • 102
0

Check the below class from https://msdn.microsoft.com/en-us/library/01escwtf(v=vs.110).aspx

using System;
using System.Globalization;
using System.Text.RegularExpressions;

public class RegexUtilities
{
   bool invalid = false;

   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;
       }
   }

   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;
   }
}

Or take a look at @Cogwheel answer here C# code to validate email address

Community
  • 1
  • 1
StackTrace
  • 9,190
  • 36
  • 114
  • 202
  • You should not be using regex for email address validation, it's built-in to the framework! – BrainSlugs83 Jun 22 '17 at 21:56
  • @BrainSlugs83 tell us where it is built in please. new MailAddress() in a try catch fails because it accepts display names aswell and the other class I found is EmailAddressAttribute.IsValid from using System.ComponentModel.DataAnnotations. – Jan Sep 19 '17 at 07:20
0

Regular expression for e-mail address can be matched using below :

 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]{2,17}))$", 
              RegexOptions.IgnoreCase);

Reference MSDN

But in your case :

fulya_42_@hotmail.coö

If you are checking the validity of email address from the ".coo" which is not valid as per your observation, it will not show any error as the regex doesnt validate that,hence you have to manually add some domains which you accept like : gmail.com , yahoo.com etc.

rightly said in the comments for the question by SonerGonul

Thanks

Tharif
  • 13,794
  • 9
  • 55
  • 77
  • is this valid email or not : pokemonozcan-24@hotmail.com – Furkan Gözükara May 26 '15 at 12:34
  • am afraid with that question ! – Tharif May 26 '15 at 12:36
  • You should not be using regex for email address validation, it's built-in to the framework! – BrainSlugs83 Jun 22 '17 at 21:56
  • @BrainSlugs83 ,please try validating addresses with your code: "Abc.@example.com" , "Abc..123@example.com" , "fulya_42_@hotmail.coö" .. – Tharif Jun 23 '17 at 02:55
  • 1
    @tharif underscores are allowed anywhere in the `local-part` of an email address (even at the end, even multiple in a row, even `_._@example.com`, which your code fails to recognize as valid). This is because `_` is a valid `atext` character (as defined by RFC 5322); as for the ending / repeating dots, those are not valid `dot-atoms`, so, without quotes, those addresses would be in violation the RFC; However, it's kind of on the provider to police that (and over the years, some haven't). -- My guess is that the .NET framework creators decided to err on the side of caution there. ¯\\_(ツ)_/¯ – BrainSlugs83 Sep 16 '17 at 00:32
  • @BrainSlugs83 appreciate your thoughts and thank you for sharing – Tharif Sep 16 '17 at 02:05
0

First off, the email address you provided is in a valid format. -- You can take it a step further and verify if the domain is valid or not as well, if you like; but either way, you should be validating ownership, in which case, you will know that the email address and domain are valid.

Secondly, you should really not be using Regex to validate an email address; email address validation is built-in to the .NET framework, and you shouldn't be recreating the wheel for something like this.

A simple validation function that performs both checks, looks like this:

public static bool IsValidEmailAddress(string emailAddress, bool verifyDomain = true)
{
    var result = false;
    if (!string.IsNullOrWhiteSpace(emailAddress))
    {
        try
        {
            // Check Format (Offline).
            var addy = new MailAddress(emailAddress);

            if (verifyDomain)
            {
                // Check that a valid MX record exists (Online).
                result = new DnsStubResolver().Resolve<MxRecord>(addy.Host, RecordType.Mx).Any();
            }
            else
            {
                result = true;
            }
        }
        catch (SocketException)
        {
            result = false;
        }
        catch (FormatException)
        {
            result = false;
        }
    }

    return result;
}

To run the code, you will need to install the NuGet package ARSoft.Tools.Net, which is required for MX record lookup*, and you will need to add the appropriate using declarations for the various classes used (should be pretty automatic in VisualStudio these days).

(*: Simply checking for a valid host name via System.Net.Dns.GetHost* is not enough, as that can give you some false negatives for some domains which only have MX entries, such as admin@fubar.onmicrosoft.com, etc.)

BrainSlugs83
  • 6,214
  • 7
  • 50
  • 56
  • I dont know about the MX Record validation, but new MailAddress("FooBar Some@thing.com") will fail, since it will result in .DisplayName = FooBar and .Address = Some@thing.com. I have seen a return obj.Address = inputEmailAddress as a work around. I am looking for another .Net way, since I think selfmade regex is not a good aproach. Maybe System.ComponentModel.DataAnnotations and its EmailAddressAttribute.IsValid() method? – Jan Sep 19 '17 at 07:27