RRR
RRR

Reputation: 4175

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?

Upvotes: 1

Views: 1572

Answers (2)

shf301
shf301

Reputation: 31404

I'm not going to even try to decode that huge regex, use the Uri.IsWellFormedUriString method instead. That already does what you are looking for.

Upvotes: 2

Oded
Oded

Reputation: 499352

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;

Upvotes: 3

Related Questions