Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 68 lines (52 sloc) 2.137 kb
4c50764 Added postcode filters and validators
Paul Court authored
1 <?php
2
df8725b Restructured Postcode stuff
Paul Court authored
3 class Pmc_Postcode_Validate extends Zend_Validate_Abstract
4c50764 Added postcode filters and validators
Paul Court authored
4 {
5 const NOT_POSTCODE = 'notPostcode';
6
7 protected $_messageTemplates = array(
8 self::NOT_POSTCODE => 'value is not a valid UK postcode'
9 );
10
11 protected $_messageVariables = array(
12
13 );
14
15
16 public function isValid($value, $context = null)
17 {
18 $value = (string) $value;
19 $this->_setValue($value);
20 $ok = true;
21
761cd2e @gargoyle Corrections to Postcode locations and some improvements to the postcode ...
authored
22 // Normalise the string into uppercase A-Z and 0-9 only. (Space is removed if it was supplied!)
23 $value = preg_replace('/[^A-Z0-9]/', '', strtoupper($value));
24
25 // Min valid length is 5 - check first so that the substr's below work as expected.
26 if (strlen($value) < 5) {
27 $this->_error(self::NOT_POSTCODE);
28 return false;
29 }
30
31 // Split the postcode into it's two parts. Part 2 is always the last 3 chars.
32 $part1 = substr($value, 0, strlen($value) - 3);
33 $part2 = substr($value, strlen($value) - 3, 3);
4c50764 Added postcode filters and validators
Paul Court authored
34
761cd2e @gargoyle Corrections to Postcode locations and some improvements to the postcode ...
authored
35 // Check the normalised parts using rules at :-
36 // http://www.cabinetoffice.gov.uk/govtalk/schemasstandards/e-gif/datastandards/address/postcode.aspx
37
38 // First half must match these 4 rules...
39 $p1 = '[ABCDEFGHIJKLMNOPRSTUWYZ]'; // required
40 $p2 = '[ABCDEFGHKLMNOPQRSTUVWXY0-9]'; // required
41 $p3 = '[ABCDEFGHJKSTUW0-9]?'; // optional
42 $p4 = '[ABEHMNPRVWXY0-9]?'; // optional
43 $part1Pattern = '/^('.$p1.$p2.$p3.$p4.')/';
44
45 // Part two must match this pattern...
46 $part2Pattern = '/([0-9][ABDEFGHJLNPQRSTUWXYZ][ABDEFGHJLNPQRSTUWXYZ])/';
47
48 // Or the special case
49 $specialPattern = 'GIR0AA';
50
51 if (preg_match($part1Pattern, $part1) == 0) {
52 $ok = false;
53 }
54 if (preg_match($part2Pattern, $part2) == 0) {
55 $ok = false;
56 }
57 if ($value == $specialPattern) {
58 $ok = true;
59 }
60
61 if (!$ok) {
62 $this->_error(self::NOT_POSTCODE);
63 return false;
64 }
4c50764 Added postcode filters and validators
Paul Court authored
65
66 return true;
67 }
68 }
Something went wrong with that request. Please try again.