Re: Domain Name validation

Posted by Bram on September 30, 2007

In Reply to Domain Name validation posted by devolution on September 18, 2007

: I'm trying to work out a Domain Name validation function for use in a utility I'm writing.
: I'm working primarily with UK domains (, and and the general name rules are as follows:
: * Characters allowed: A-Z, 0-9 and hyphens
: * No hyphens at start or end of domain
: * Domain must be at least 2 characters
: Examples of valid domains:
: Examples of invalid domains:
:,, moneyŁ
: I'm looking to put together a function to validate a string to see if it is a valid domain name. Plus I wish to know if it is a domain with extension (eg: or just the 'keyword' (eg: music).

Nice Delphi coding puzzle, I enjoyed solving it ;)
Here is my code:

  Extens: array[0..2] of string = ('', '', '');
function IsKeyword(S: string): Boolean;
  Result := Pos('.', S) = 0;
function IsValid(S: string): Boolean;
  FirstPart, Ext: string;
  i: integer;
  if IsKeyword(S) then FirstPart := S
  else FirstPart := Copy(S, 1, Pos('.', S) - 1);
  Result := (Length(FirstPart) > 1) and
    (FirstPart[1]  '-') and (FirstPart[Length(FirstPart)]  '-');
  if Result then
    for i := 1 to Length(FirstPart) do begin
      Result := FirstPart[i] in ['A'..'Z', 'a'..'z', '0'..'9', '-'];
      if not Result then break;
  if Result and (not IsKeyword(S)) then begin
    Ext := LowerCase(Copy(S, Pos('.', S) + 1, Length(S)));
    for i := Low(Extens) to High(Extens) do begin
      Result := Ext = LowerCase(Extens[i]);
      if Result then break;

Succes with the source code!