Skip to content

Commit

Permalink
Added postcode validation
Browse files Browse the repository at this point in the history
  • Loading branch information
Jordan Hall committed Jan 16, 2017
1 parent e601d47 commit fa7f406
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 6 deletions.
19 changes: 14 additions & 5 deletions Example.php
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
<?php
require_once 'vendor/autoload.php';
use \RapidWeb\Postcodes\Utils\Validator;
use \RapidWeb\Postcodes\Factories\IdealPostcodesFactory;

// You should specify IDEAL_POSTCODES_API_KEY in your .env file,
// or pass it via the getByAPIKey method.
$postcode = 'ST163DP';

$idealPostcodes = IdealPostcodesFactory::getByEnvironment();
$validated = Validator::validatePostcode($postcode);

$addresses = $idealPostcodes->getAddressesByPostcode('ST163DP');
if ($validated) {

var_dump($addresses);
// You should specify IDEAL_POSTCODES_API_KEY in your .env file,
// or pass it via the getByAPIKey method.

$idealPostcodes = IdealPostcodesFactory::getByEnvironment();

$addresses = $idealPostcodes->getAddressesByPostcode('ST163DP');

var_dump($addresses);

}
13 changes: 12 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,15 @@ You will receive an array of addresses, appropriately split by their address lin

```php
$addresses = $idealPostcodes->getAddressesByPostcode('ST163DP');
```
```

### Validate postcode

You can validate a UK postcode is correct using the `Validator` utility class. An example of
how to do so is shown below.

```php
$validated = \RapidWeb\Postcodes\Utils\Validator::::validatePostcode('ST163DP');
```

Please note that the postcode validation is case insensitive.
16 changes: 16 additions & 0 deletions src/Utils/Validator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php
namespace RapidWeb\Postcodes\Utils;

abstract class Validator
{
public static function validatePostcode($postcode)
{
$postcode = strtoupper($postcode);

$regex = '#^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$#';

$result = preg_match($regex, $postcode);

return $result ? true : false;
}
}

0 comments on commit fa7f406

Please sign in to comment.