Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate FQDN in C#

Tags:

c#

regex

fqdn

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?

like image 912
RRR Avatar asked Feb 06 '11 09:02

RRR


People also ask

What is FQDN validation?

This is a version that works in javascript (without regex look behind). Hostnames are composed of a series of labels concatenated with dots. Each label is 1 to 63 characters long, and may contain: the ASCII letters a-z and A-Z, the digits 0-9, and the hyphen ('-').

What is FQDN CMD?

Type "ipconfig" and press "Enter." This displays the IP address for your Windows server. Use this IP address to view the fully qualified domain name of the server.


2 Answers

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.

like image 142
bitxwise Avatar answered Oct 06 '22 04:10

bitxwise


I think this could also be an option especially if the FQDN will later be used along with System.Uri:

var isWellFormed = Uri.CheckHostName(stringToCheck).Equals(UriHostNameType.Dns);

Note that this code considers partially qualified domain names to be well formed.

like image 43
Dmitry Avatar answered Oct 06 '22 04:10

Dmitry