PHPackages                             spatie/laravel-validation-rules - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. spatie/laravel-validation-rules

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

spatie/laravel-validation-rules
===============================

A set of useful Laravel validation rules

3.4.4(2mo ago)8243.3M—0.9%456MITPHPPHP ^8.0CI passing

Since Oct 11Pushed 2mo ago12 watchersCompare

[ Source](https://github.com/spatie/laravel-validation-rules)[ Packagist](https://packagist.org/packages/spatie/laravel-validation-rules)[ Docs](https://github.com/spatie/laravel-validation-rules)[ GitHub Sponsors](https://github.com/spatie)[ RSS](/packages/spatie-laravel-validation-rules/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (7)Versions (38)Used By (6)

A set of useful Laravel validation rules
========================================

[](#a-set-of-useful-laravel-validation-rules)

[![Latest Version on Packagist](https://camo.githubusercontent.com/68914d79f037ae2d19d8c02c452955b84e025a162654f3c842e28205cb3d98d5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f6c61726176656c2d76616c69646174696f6e2d72756c65732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-validation-rules)[![Tests](https://camo.githubusercontent.com/f68f776feb2426febcea15c8df7abaa886cc20bedd70e95fbcafdf5b60253372/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7370617469652f6c61726176656c2d76616c69646174696f6e2d72756c65732f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d5465737473)](https://github.com/spatie/laravel-validation-rules/actions/workflows/run-tests.yml)[![Total Downloads](https://camo.githubusercontent.com/dccc3a12a8b95f52c9fe73c3f5491de6019c203d4f43afa4775f4cf808539d95/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f6c61726176656c2d76616c69646174696f6e2d72756c65732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-validation-rules)

This repository contains some useful Laravel validation rules.

Support us
----------

[](#support-us)

[![](https://camo.githubusercontent.com/afcadf78f93236825eaeec93b817d7c095b587c0ad38040ffd1520b6badae95f/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f6c61726176656c2d76616c69646174696f6e2d72756c65732e6a70673f743d31)](https://spatie.be/github-ad-click/laravel-validation-rules)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require spatie/laravel-validation-rules
```

The package will automatically register itself.

### Translations

[](#translations)

If you wish to edit the package translations, you can run the following command to publish them into your `resources/lang` folder

```
php artisan vendor:publish --provider="Spatie\ValidationRules\ValidationRulesServiceProvider"
```

Available rules
---------------

[](#available-rules)

- [`Authorized`](#authorized)
- [`CountryCode`](#countrycode)
- [`Currency`](#currency)
- [`Enum`](#enum)
- [`ModelsExist`](#modelsexist)
- [`Delimited`](#delimited)

### `Authorized`

[](#authorized)

Determine if the user is authorized to perform an ability on an instance of the given model. The id of the model is the field under validation

Consider the following policy:

```
class ModelPolicy
{
    use HandlesAuthorization;

    public function edit(User $user, Model $model): bool
    {
        return $model->user->id === $user->id;
    }
}
```

This validation rule will pass if the id of the logged in user matches the `user_id` on `TestModel` who's it is in the `model_id` key of the request.

```
// in a `FormRequest`

use Spatie\ValidationRules\Rules\Authorized;

public function rules()
{
    return [
        'model_id' => [new Authorized('edit', TestModel::class)],
    ];
}
```

Optionally, you can provide an authentication guard as the third parameter.

```
new Authorized('edit', TestModel::class, 'guard-name')
```

#### Model resolution

[](#model-resolution)

If you have implemented the `getRouteKeyName` method in your model, it will be used to resolve the model instance. For further information see [Customizing The Default Key Name](https://laravel.com/docs/7.x/routing)

### `CountryCode`

[](#countrycode)

Determine if the field under validation is a valid [2 letter ISO3166 country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Current_codes) (example of valid country codes: `GB`, `DK`, `NL`).

**Note** that this rule requires the package [`league/iso3166`](https://github.com/thephpleague/iso3166) to be installed: `composer require league/iso3166`

```
// in a `FormRequest`

use Spatie\ValidationRules\Rules\CountryCode;

public function rules()
{
    return [
        'country_code' => ['required', new CountryCode()],
    ];
}
```

If you want to validate a nullable country code field, you can call the `nullable()` method on the `CountryCode` rule. This way `null` and `0` are also passing values:

```
// in a `FormRequest`

use Spatie\ValidationRules\Rules\CountryCode;

public function rules()
{
    return [
        'country_code' => [(new CountryCode())->nullable()],
    ];
}
```

### `Currency`

[](#currency)

Determine if the field under validation is a valid [3 letter ISO4217 currency code](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) (example of valid currencies: `EUR`, `USD`, `CAD`).

**Note** that this rule require the package [`league/iso3166`](https://github.com/thephpleague/iso3166) to be installed: `composer require league/iso3166`

```
// in a `FormRequest`

use Spatie\ValidationRules\Rules\Currency;

public function rules()
{
    return [
        'currency' => ['required', new Currency()], // Must be present and a valid currency
    ];
}
```

If you want to validate a nullable currency field, simple do not let it be required as described in the [Laravel Docs for implicit validation rules](https://laravel.com/docs/master/validation#implicit-rules):

> ... when an attribute being validated is not present or contains an empty string, normal validation rules, including custom rules, are not run

```
// in a `FormRequest`

use Spatie\ValidationRules\Rules\Currency;

public function rules()
{
    return [
        'currency' => [new Currency()], // This will pass for any valid currency, an empty value or null
    ];
}
```

### `Enum`

[](#enum)

This rule will validate if the value under validation is part of the given enum class. We assume that the enum class has a static `toArray` method that returns all valid values. If you're looking for a good enum class, take a look at [spatie/enum](https://github.com/spatie/enum) or [myclabs/php-enum](https://github.com/myclabs/php-enum).

Consider the following enum class:

```
class UserRole extends MyCLabs\Enum\Enum
{
    const ADMIN = 'admin';
    const REVIEWER = 'reviewer';
}
```

The `Enum` rule can be used like this:

```
// in a `FormRequest`

use Spatie\ValidationRules\Rules\Enum;

public function rules()
{
    return [
        'role' => [new Enum(UserRole::class)],
    ];
}
```

The request will only be valid if `role` contains `ADMIN` or `REVIEWER`.

### `ModelsExist`

[](#modelsexist)

Determine if all of the values in the input array exist as attributes for the given model class.

By default the rule assumes that you want to validate using `id` attribute. In the example below the validation will pass if all `model_ids` exist for the `Model`.

```
// in a `FormRequest`

use Spatie\ValidationRules\Rules\ModelsExist;

public function rules()
{
    return [
        'model_ids' => ['array', new ModelsExist(Model::class)],
    ];
}
```

You can also pass an attribute name as the second argument. In the example below the validation will pass if there are users for each email given in the `user_emails` of the request.

```
// in a `FormRequest`

use Spatie\ValidationRules\Rules\ModelsExist;

public function rules()
{
    return [
        'user_emails' => ['array', new ModelsExist(User::class, 'emails')],
    ];
}
```

### `Delimited`

[](#delimited)

This rule can validate a string containing delimited values. The constructor accepts a rule that is used to validate all separate values.

Here's an example where we are going to validate a string containing comma separated email addresses.

```
// in a `FormRequest`

use Spatie\ValidationRules\Rules\Delimited;

public function rules()
{
    return [
        'emails' => [new Delimited('email')],
    ];
}
```

Here's some example input that passes this rule:

- `'sebastian@example.com, alex@example.com'`
- `''`
- `'sebastian@example.com'`
- `'sebastian@example.com, alex@example.com, brent@example.com'`
- `' sebastian@example.com   , alex@example.com  ,   brent@example.com  '`

This input will not pass:

- `'@example.com'`
- `'nocomma@example.com nocommatoo@example.com'`
- `'valid@example.com, invalid@'`

#### Setting a minimum

[](#setting-a-minimum)

You can set minimum amout of items that should be present:

```
(new Delimited('email'))->min(2)
```

- `'sebastian@example.com, alex@example.com'` // passes
- `'sebastian@example.com'` // fails

#### Setting a maximum

[](#setting-a-maximum)

```
(new Delimited('email'))->max(2)
```

- `'sebastian@example.com'` // passes
- `'sebastian@example.com, alex@example.com, brent@example.com'` // fails

#### Allowing duplicate items

[](#allowing-duplicate-items)

By default the rule will fail if there are duplicate items found.

- `'sebastian@example.com, sebastian@example.com'` // fails

You can allowing duplicate items like this:

```
(new Delimited('numeric'))->allowDuplicates()
```

Now this will pass: `1,1,2,2,3,3`

#### Customizing the separator

[](#customizing-the-separator)

```
(new Delimited('email'))->separatedBy(';')
```

- `'sebastian@example.com; alex@example.com; brent@example.com'` // passes
- `'sebastian@example.com, alex@example.com, brent@example.com'` // fails

#### Skip trimming of items

[](#skip-trimming-of-items)

```
(new Delimited('email'))->doNotTrimItems()
```

- `'sebastian@example.com,freek@example.com'` // passes
- `'sebastian@example.com, freek@example.com'` // fails
- `'sebastian@example.com , freek@example.com'` // fails

#### Composite rules

[](#composite-rules)

The constructor of the validator accepts a validation rule string, a validate instance, or an array.

```
new Delimited('email|max:20')
```

- `'short@example.com'` // passes
- `'invalid'` // fails
- `'loooooooonnnggg@example.com'` // fails

#### Passing custom error messages

[](#passing-custom-error-messages)

The constructor of the validator accepts a custom error messages array as second parameter.

```
// in a `FormRequest`

use Spatie\ValidationRules\Rules\Delimited;

public function rules()
{
    return [
        'emails' => [new Delimited('email', $this->messages())],
    ];
}

public function messages()
{
    return [
        'emails.email' => 'Not all the given e-mails are valid.',
    ];
}
```

### Testing

[](#testing)

```
composer test
```

### Changelog

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

### Security

[](#security)

If you've found a bug regarding security please mail  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Freek Van der Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)

Support us
----------

[](#support-us-1)

Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).

Does your business depend on our contributions? Reach out and support us on [Patreon](https://www.patreon.com/spatie). All pledges will be dedicated to allocating workforce on maintenance and new awesome stuff.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

69

—

FairBetter than 100% of packages

Maintenance83

Actively maintained with recent releases

Popularity65

Solid adoption and visibility

Community37

Small or concentrated contributor base

Maturity78

Established project with proven stability

 Bus Factor1

Top contributor holds 66.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~76 days

Recently: every ~180 days

Total

36

Last Release

86d ago

Major Versions

0.0.2 → 1.0.02018-10-12

1.0.3 → 2.0.02018-12-19

2.7.1 → 3.0.02020-11-30

PHP version history (5 changes)0.0.1PHP ^7.1

2.1.1PHP ^7.2

2.7.1PHP ^7.3|^8.0

3.2.0PHP ^7.4|^8.0

3.2.2PHP ^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (173 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (9 commits)")[![imdhemy](https://avatars.githubusercontent.com/u/22864831?v=4)](https://github.com/imdhemy "imdhemy (8 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (8 commits)")[![lloricode](https://avatars.githubusercontent.com/u/8251344?v=4)](https://github.com/lloricode "lloricode (7 commits)")[![Nielsvanpach](https://avatars.githubusercontent.com/u/10651054?v=4)](https://github.com/Nielsvanpach "Nielsvanpach (6 commits)")[![laravel-shift](https://avatars.githubusercontent.com/u/15991828?v=4)](https://github.com/laravel-shift "laravel-shift (6 commits)")[![carestad](https://avatars.githubusercontent.com/u/65263?v=4)](https://github.com/carestad "carestad (5 commits)")[![Gummibeer](https://avatars.githubusercontent.com/u/6187884?v=4)](https://github.com/Gummibeer "Gummibeer (4 commits)")[![e-nikitin](https://avatars.githubusercontent.com/u/15894528?v=4)](https://github.com/e-nikitin "e-nikitin (4 commits)")[![bilfeldt](https://avatars.githubusercontent.com/u/30228807?v=4)](https://github.com/bilfeldt "bilfeldt (4 commits)")[![lnpbk](https://avatars.githubusercontent.com/u/608543?v=4)](https://github.com/lnpbk "lnpbk (3 commits)")[![vkosciuszko](https://avatars.githubusercontent.com/u/27742874?v=4)](https://github.com/vkosciuszko "vkosciuszko (2 commits)")[![atymic](https://avatars.githubusercontent.com/u/50683531?v=4)](https://github.com/atymic "atymic (2 commits)")[![cochondeguerre](https://avatars.githubusercontent.com/u/272151221?v=4)](https://github.com/cochondeguerre "cochondeguerre (2 commits)")[![dmitrybubyakin](https://avatars.githubusercontent.com/u/11477505?v=4)](https://github.com/dmitrybubyakin "dmitrybubyakin (2 commits)")[![ragulka](https://avatars.githubusercontent.com/u/593267?v=4)](https://github.com/ragulka "ragulka (2 commits)")[![thibaultlavoisey](https://avatars.githubusercontent.com/u/2022117?v=4)](https://github.com/thibaultlavoisey "thibaultlavoisey (2 commits)")[![travisobregon](https://avatars.githubusercontent.com/u/12074713?v=4)](https://github.com/travisobregon "travisobregon (2 commits)")[![mcordingley](https://avatars.githubusercontent.com/u/1084253?v=4)](https://github.com/mcordingley "mcordingley (1 commits)")

---

Tags

laravelphprulesvalidationspatielaravel-validation-rules

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/spatie-laravel-validation-rules/health.svg)

```
[![Health](https://phpackages.com/badges/spatie-laravel-validation-rules/health.svg)](https://phpackages.com/packages/spatie-laravel-validation-rules)
```

###  Alternatives

[spatie/laravel-honeypot

Preventing spam submitted through forms

1.6k6.0M60](/packages/spatie-laravel-honeypot)[proengsoft/laravel-jsvalidation

Validate forms transparently with Javascript reusing your Laravel Validation Rules, Messages, and FormRequest

1.1k2.3M49](/packages/proengsoft-laravel-jsvalidation)[stevebauman/purify

An HTML Purifier / Sanitizer for Laravel

5325.6M19](/packages/stevebauman-purify)[axlon/laravel-postal-code-validation

Worldwide postal code validation for Laravel and Lumen

3853.3M1](/packages/axlon-laravel-postal-code-validation)[laravel-validation-rules/credit-card

Validate credit card number, expiration date, cvc

2412.2M5](/packages/laravel-validation-rules-credit-card)[illuminatech/validation-composite

Allows uniting several validation rules into a single one for easy re-usage

184485.5k](/packages/illuminatech-validation-composite)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
