The above regex of \b\d{5}\b
uses word boundaries and would pass validation as long as there are 5 grouped digits anywhere in the input. This is probably not what most people want.
For example, if the user submits Hello 00000 World!
, validation would pass and your controller would receive the string Hello 00000 World!
which is most likely not what it would be expecting and it would cry.
Validate 5 Digits (Zip)
I would suggest using anchors since all we want is 5 digits and absolutely nothing else to pass validation and in to the controller.
Something like this is simple and would work for 5 digits (a zip code):
protected static $rules = [
'zip_code' => 'required|regex:/^\d{5}$/'
];
Validate 5 Digits a dash, and 4 Digits (Zip + 4)
Or, if you want to validate Zip+4, ie. 12345-6789
formatted zip codes you could do something like this:
protected static $rules = [
'zip_code' => 'required|regex:/^\d{5}-\d{4}$/'
];
That would let 12345-6789
through, but not 1234-56789
or 123456789
, etc.
Then something like this to handle it:
$zip = explode('-', $request->input('zip_code'));
$zip[0]
would have 12345
, which is the zip.
$zip[1]
would have 6789
, which is the +4.
Validate Either (Zip or Zip + 4)
Or, let's say you want to accept and validate either zip or zip+4 depending on what the user submitted. You could do something like this:
protected static $rules = [
'zip_code' => 'required|regex:/^\d{5}(?:-\d{4})?$/'
];
That would let 12345
and 12345-6789
but fail on anything else.
Then you could the same as above since explode will still work on both variants but build an array of either one or two values depending.
$zip = explode('-', $request->input('zip_code'));
if (count($zip) > 1) {
// do some zip+4 stuff
} else {
// just a zip, lets do zip stuff
}