Delphi Validating UK postcodes

By | June 4, 2012

http://www.daniweb.com/software-development/pascal-and-delphi/threads/276733/postcode-validation
http://www.ml-consult.co.uk/foxst-39.htm

function ValidPostcode(anInput: String): Boolean;
var
  iSpacePos, I: byte;
  sInward, sOutward: String;
begin
  Result := False;
  if (anInput = EmptyStr) then
    Exit;
  anInput := UpperCase(anInput);
  iSpacePos := Pos(' ', anInput);
  if iSpacePos = 0 then
    Exit;
  sInward := Copy(anInput, iSpacePos + 1, 3);
  sOutward := Copy(anInput, 1, iSpacePos - 1);

  if StrToIntDef(sInward[1], -1) = -1 then
    Exit; // first char has to be a number
  // these characters never appear in the inward code
  if (AnsiIndexStr(sInward[2], ['C', 'I', 'K', 'M', 'O', 'V']) <> -1) or (AnsiIndexStr(sInward[3], ['C', 'I', 'K', 'M', 'O', 'V']) <> -1) then
    Exit;
  // build the outward code as the patterns from the site
  for I := 1 to Length(sOutward) do
    if ord(sOutward[I]) in [65 .. 90] then // or sOutward[i] in ['A'..'Z']
      sOutward[I] := 'A'
    else
      sOutward[I] := '9';

  if AnsiIndexStr(sOutward, ['A9', 'A99', 'AA9', 'A9A', 'AA99', 'AA9A']) = -1 then
    Exit;
  // the code is valid, so i return true value
  Result := true;

end;