Last active
March 30, 2022 22:25
-
-
Save arimolzer/0e26b0915c3f0957472b4aa11f83db1b to your computer and use it in GitHub Desktop.
Laravel 9.* validation rule to check that the format of a provided string matches the required format for Australian drivers licences.
This file contains hidden or 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 Illuminate\Contracts\Validation\Rule; | |
| class AustralianDriversLicence implements Rule | |
| { | |
| /** | |
| * Determine if the validation rule passes. | |
| * | |
| * @param string $attribute | |
| * @param mixed $value | |
| * @return bool | |
| */ | |
| public function passes($attribute, $value): bool | |
| { | |
| // 1. Max length 9 characters | |
| // 2. Alphanumeric characters only | |
| // 3. Must have at least 4 numeric characters | |
| // 4. Must have no more than 2 alphabetic characters | |
| // 5. The third and fourth character must be numeric | |
| return ( | |
| strlen($value) <= 9 | |
| && ctype_alnum($value) | |
| && preg_match_all('/[0-9]/', $value) >= 4 | |
| && preg_match('/[0-9]{3}/', $value) | |
| && preg_match('/[0-9]{4}/', $value) | |
| ); | |
| } | |
| /** | |
| * Get the validation error message. | |
| * | |
| * @return string | |
| */ | |
| public function message(): string | |
| { | |
| return __('The provided drivers licence is not valid.'); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment