Can someone please help me - I need to write a function that will validate UK postcodes written in a textbox but every tutorial and example source code I find for it is in other languages such as VB and Javascript.

The VB code looks extremely small:

1.
Public Function isValidPostCode(ByVal input As String) As Boolean
2.

3.
Dim validInput As Boolean = False
4.

5.
' Check that the input is not null before checking
6.
If input IsNot Nothing Then
7.

8.
' Regex from: http://www.cabinetoffice.gov.uk/media/291370/bs7666-v2-0-xsd-PostCodeType.htm
9.
validInput = Regex.IsMatch(input, "^(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2})$", RegexOptions.IgnoreCase)
10.

11.
End If
12.

13.
Return validInput
14.

15.
End Function

Is there a way this could be convereted for use in Delphi database?

Recommended Answers

You're welcome, but you have found your answer, please mark the thread as solved.

Ionut

Jump to Post

All 3 Replies

I don't think that Delphi has any function to parse regular expressions, so I looked on this site http://www.ml-consult.co.uk/foxst-39.htm and found some informations from which i built the following function

function TForm1.CheckIfValid(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;

If you want to create a more accurate validation, read the entire article from the link I posted.

Ionut

Thank you so very much, you have really helped me a lot.

You're welcome, but you have found your answer, please mark the thread as solved.

Ionut

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.