In Laravel, what validation rules do I need to check the number of characters in a number?

zeckdude picture zeckdude · Feb 11, 2015 · Viewed 10.5k times · Source

I'm using rules in validation in Laravel, and am trying to check the number of characters in a number.

This is my attempt:

protected static $rules = [
    'zip_code' => 'required|size:5|integer'
];

Unfortunately that checks that the zip code is the number 5 and not that the zip code is 5 characters. Which rules do I need to set to check that the zip code is exactly 5 characters, regardless of the actual numbers?

Answer

Bogdan picture Bogdan · Feb 11, 2015

A zip code is 5 digits long and may contain leading zeros (Northeast US). The Laravel "digits" check drops the leading zeros as a result you need to use a regex pattern:

protected static $rules = [
     'zip_code' => 'required|regex:/\b\d{5}\b/'
];

This will make sure the zip code is always 5 digits long. More details in the Laravel Docs