Search code examples
c#regexfqdn

Validate FQDN in C#


Does anyone have a Regular Expression to validate legal FQDN?

Now, I use on this regex:

(?=^.{1,254}$)(^(?:(?!\d+\.|-)[a-zA-Z0-9_\-]{1,63}(?!-)\.?)+(?:[a-zA-Z]{2,})$)

However this regex results in "aa.a" not being valid while "aa.aa" is valid.

Does anyone know why?


Solution

  • Here's a shorter pattern:

    (?=^.{1,254}$)(^(?:(?!\d+\.)[a-zA-Z0-9_\-]{1,63}\.?)+(?:[a-zA-Z]{2,})$)
    

    As for why the pattern determines "aa.a" as invalid and "aa.aa" as valid, it's because of the {2,} - if you change the 2 to a 1 so that it's

    (?=^.{1,254}$)(^(?:(?!\d+\.)[a-zA-Z0-9_\-]{1,63}\.?)+(?:[a-zA-Z]{1,})$)
    

    it should deem both "aa.a" and "aa.aa" as valid.

    string pattern = @"(?=^.{1,254}$)(^(?:(?!\d+\.)[a-zA-Z0-9_\-]{1,63}\.?)+(?:[a-zA-Z]{1,})$)";
    bool isMatch = Regex.IsMatch("aa.a", pattern);
    

    isMatch is TRUE for me.