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 (.co.uk, .org.uk and .me.uk) 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:
: music.co.uk, blah.org.uk, we-3.me.uk
: Examples of invalid domains:
: x.co.uk, -ssd.org.uk, moneyŁ.me.uk
: 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: music.co.uk) or just the 'keyword' (eg: music).

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

const
  Extens: array[0..2] of string = ('co.uk', 'org.uk', 'me.uk');
  
function IsKeyword(S: string): Boolean;
begin
  Result := Pos('.', S) = 0;
end;
  
function IsValid(S: string): Boolean;
var
  FirstPart, Ext: string;
  i: integer;
begin
  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;
    end;
  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;
    end;
  end;
end;

Succes with the source code!
Bram