Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 948
zeckdude Avatar asked Feb 10 '15 23:02

zeckdude


1 Answers

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

like image 199
Bogdan Avatar answered Nov 12 '22 14:11

Bogdan