Search code examples
c#regexfqdn

Validate FQDN in C# using regex


I wrote the following pattern in C# to validate a FQDN received from a user:

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

I want to allow the user to enter the following FQDN:

<name>.<letter><digit>

such as "aa.a1". For "aa.a1" my regex detects the FQDN as invalid, and for "aa.1a" it detects it as valid. Does anyone know why?


Solution

  • Instead of using a RegEx, you can load the string into a Uri and use the different methods and properties to figure out if it is a FQDN.

    Uri uri = new Undri(myFQDN);
    string host = uri.Host;
    bool isAbsolute = uri.IsAbsoluteUri;