Blog Detail

20

Aug
A set of useful Laravel validation rules cover image

arrow_back A set of useful Laravel validation rules

Spatie comes up with a set of some useful Laravel validation rules, which you can easily utilize in your laravel web applications. This set includes the following validation rules:

  • Authorized
  • CountryCode
  • Currency
  • Enum
  • ModelsExist
  • Delimited

Installation

You can install this package via composer by running this command:

composer require spatie/laravel-validation-rules

The package will automatically register itself.

Translations

If you want to edit the package translations, you’ve to run the following command to publish them into your resources/lang folder

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

Available Rules

These are the rules available in this package:

Authorized

This rule determines if the user is authorized to perform an ability on an instance of the given model. The id of the model in 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')

Currency

Currency rule determines if the field under validation is a valid 3 letter ISO4217 currency code (example of valid currencies: EUR, USD, CAD).

Note that this rule requires the package league/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
    ];
}

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 searching for a good enum class, take a look at spatie/enum or 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 utilized 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 the role includes ADMIN or REVIEWER.

ModelsExist

This rule determines 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 employing the 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

This rule can validate a string containing delimited values. The constructor accepts a rule that is utilized 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@'

There are many other options available in this package. If you want to explore it more, you can visit its detailed documentation on Github.

Published at : 20-08-2021

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project