Skip to content
Advertisement

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

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?

Advertisement

Answer

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:/bd{5}b/'
];

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

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement