How to Implement a Custom Laravel Zip Code Validation Rule

The following class1 makes a new zip validation rule available to your Laravel2 validators. It validates 5-digit U.S. postal codes, and the ZIP+4 format.

<?php namespace Path\To\Validators;

use Illuminate\Validation\Validator;

class ZipValidator extends Validator
    public function validateZip($attribute, $value, $parameters)
        return preg_match('/^[0-9]{5}(\-[0-9]{4})?$/', $value);

Store the ZipValidator class in a location of your choosing (making sure to set the namespace accordingly), and tell Laravel about its existence.

Example usage:

$rules = [
    'postcode' => ['required', 'zip'],

  1. As with much on this blog, this post is essentially a note to self. I’m sure I’ve written this class—or something very similar—multiple times, and it seems unlikely I’ll ever get around to creating a package for it. Hopefully the next time I need to validate a zip code in Laravel, Google will remind me of the existence of this blog post. ↩︎

  2. Tested in Laravel 4.2. ↩︎

Bend Craft to Your Will

Our newsletter helps you make the most of Craft. Join for free, leave any time.