Validating Max Length in Laravel – Also for Integers and Digits

Validating Max Length in Laravel

I recently figured that Laravel does not have a validation rule for max length. Sure, you could use “max”, but if you also use the “integer” validation, this will cause “max” to be the max value, not length.

I recently tweeted this:

It’s quite simple, you specify a custom validation rule that checks the length of the value.

Add this to your service providers (Eg. AppServiceProvider) boot() method

\Validator::extend( 'maxlength', function ( $attribute, $value, $parameters, $validator )
{
   return mb_strlen( $value ) <= (int) $parameters[0];
} );

Validation messages

You’ll probably want to have a fitting validation message as well, which is also quite simple. First, you’ll want to add another block of content to your boot() method.

\Validator::replacer( 'maxlength', function ( $message, $attribute, $rule, $parameters )
{
   return str_replace( ':maxlength', $parameters[0], $message );
} );

And in your resources/lang/{LOCALE}/validation.php file, add this line to the first level of the array:

'maxlength' => 'The :attribute field may not be more than :maxlength characters of length.',

Of cause, you can fit this to your liking. Doing this, will return something like:

The number field may not be more than 10 characters of length.

Final thought

To me, this should be core functionality, and I might also submit a PR for this, but until then, using a custom rule is a great solution.

More useful snippets

If you’re interested in great snippets, not only for Laravel, but also Vue, JavaScript, PHP and much much more, you should checkout Tweetsnippet, a curated collection of snippets from tweets.

Lasse Rafn
I'm a frontend and backend developer, primarily using Vue and Laravel.

Leave a Comment

Your email address will not be published. Required fields are marked *