6

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?

Kiquenet
  • 14,494
  • 35
  • 148
  • 243
RRR
  • 3,937
  • 13
  • 51
  • 75

2 Answers2

4

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.

Dmitry
  • 17,078
  • 2
  • 44
  • 70
4

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.

bitxwise
  • 3,534
  • 2
  • 17
  • 22
  • I do that but it's not work, again it determines "aa.a" as invalid and "aa.aa" as valid. can you explain me what the meaning of "{1,}" instead "{2,}"? – RRR Feb 06 '11 at 09:59
  • Using the pattern with `{1.}` "aa.a" validates for me. Curly braces specify a specific amount of repetition so `{1,}` requires at least 1 repetition and `{2,}` requires at least 2. – bitxwise Feb 06 '11 at 10:07
  • Additional question, what are the diffrents between the pattern that you suggest me to the pattern that I use? – RRR Feb 06 '11 at 10:17
  • Only difference is that yours has `(?!-).?)` for the last dot and the one I posted has `\.?)`. The `?!` in yours is using a _negative lookahead assertion_ ("match something not followed by something else"). – bitxwise Feb 06 '11 at 10:27
  • now I want to allow also "aa.a10", I change the regex to: (@"(?=^.{1,254}$)(^(?:(?!\d+\.)[a-zA-Z0-9_\-]{1,63}\.?)+(?:[a-zA-Z0-9]{1,})$)") but it's not work, do you know why? – RRR Feb 06 '11 at 11:40
  • @RRR: It works for me...try putting isolating the pattern with your "aa.a10" entry. – bitxwise Feb 06 '11 at 21:48