0

I am having a problem validating domains. What am I doing wrong?

        Regex re = new Regex("^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\\.[a-zA-Z]{2,}$");
        if (re.IsMatch(domain.Text))
//          if (Regex.IsMatch(domain.Text, @"^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\\.[a-zA-Z]{2,}$"))
            warningLabel.Text = "Domain format is invalid!";    // domain: " + domain.Text;

I checked with Regex checker and got "your pattern matches but there were no (capturing (groups)) in it that matched anything in the subject string."

Why I don't get errors on invalid characters?

Thank you.

Moshe Shmukler
  • 1,116
  • 2
  • 18
  • 35

1 Answers1

1

your Regex is basically correct (but see link below), and this test method confirms it:

public static void Test()
        {
            Regex re = new Regex("^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\\.[a-zA-Z]{2,}$");
            var m=re.Match("test.com");
            Console.WriteLine(m.Groups[0].Value);
            m=   re.Match("more-messy-domain-0234-example.xx");
            Console.WriteLine(m.Groups[0].Value);
       }

This outputs:

test.com

more-messy-domain0234-example.xx

Note there is a good discussion of regex for domain names here: Domain name validation with RegEx

There are some subtle situations which are not included in your regex.

Community
  • 1
  • 1
shelbypereira
  • 1,655
  • 2
  • 21
  • 42