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

Selec All Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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;