Created
July 25, 2023 14:18
-
-
Save liamja/515014122003c3d81c5271777c56453a to your computer and use it in GitHub Desktop.
UK Postcode Validation Rule for Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Rules; | |
use Closure; | |
use Illuminate\Contracts\Validation\ValidationRule; | |
/** | |
* UK Postcode Validation Rule. | |
* | |
* The following is the UK Postcode Regular Expression and the corresponding | |
* detail explaining the logic behind the UK Postcode Regular Expression. | |
* | |
* Logic: | |
* "GIR 0AA" | |
* OR | |
* One letter followed by either one or two numbers | |
* OR | |
* One letter followed by a second letter that must be one of ABCDEFGHJ | |
* KLMNOPQRSTUVWXY (i.e..not I) and then followed by either one or two | |
* numbers | |
* OR | |
* One letter followed by one number and then another letter | |
* OR | |
* A two part post code | |
* where the first part must be | |
* One letter followed by a second letter that must be one of ABCDEFGH | |
* JKLMNOPQRSTUVWXY (i.e..not I) and then followed by one number and | |
* optionally a further letter after that | |
* AND | |
* The second part (separated by a space from the first part) must be One | |
* number followed by two letters. | |
* | |
* A combination of upper and lower case characters is allowed. | |
* | |
* Note: the length is determined by the regular expression and is between 2 and 8 | |
* characters. | |
*/ | |
class Postcode implements ValidationRule | |
{ | |
/** | |
* Run the validation rule. | |
* | |
* @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail | |
*/ | |
public function validate(string $attribute, mixed $value, Closure $fail): void | |
{ | |
if (! preg_match('/^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$/', $value)) { | |
$fail('The :attribute must be a valid UK postcode.'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment