Validate a UK Grid Reference in Laravel 5
· 251 wordsThis will just be a small article and quite a specific one. We’ll be looking at how to verify an input to guarantee it is a valid 8 figure grid reference. This will be checking against the UK Ordnance Survey standard, so two letters followed by four easting numbers and four northing numbers.
e.g. AA11112222
It is important to remove any spaces from the string before submitting. This can be achieved through a small JS function and a .replace function. The reason this must be done is because we will be checking the length of the string, spaces included.
If you’re using Laravel 5 then you’ll be able to change your Request
class. This is where the validation rules are decided for each form submission. In Laravel 4 you can still use this, but will need to be in the Model or Controller – how ever you have it set up.
public function rules() {
return [
'grid_reference' => ['required', 'string', 'size:10', 'regex:/[a-zA-Z]{2}[\d+]{8}/']
];
}
Usually with validation rules you can pass a string, separated by the pipe character. When using regex as a rule however, you should pass it as an array (because the pipe character can be considered as part of the regex).
Because the string we passed in the request had all the spaces stripped from it, the regex checks for two characters at the start with [a-zA-Z]{2}
then checks for a following 8 numbers with [\d+]{8}
.
So there we have it, simple as that. Happy Validating.