Laravel provides plenty of validation rules, but what if you need to add your own? We’ll show you how to do it, with the rule “the maximum number of words is 500”, and we will also make this number of 500 a parameter.

Step 1. Generate validation rule

Since Laravel 5.5 we have the possibility to generate a special class where we can specify all the parameters we need:


php artisan make:rule MaxWordsRule

It generates this file – app/Rules/MaxWordsRule.php:


namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class MaxWordsRule implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        //
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The validation error message.';
    }
}

Step 2. Fill in the validation rule and error message

We need to populate our implementation of these methods above. Method pass() should return true/false based on the value, and message() should return an error message, and it can use :attribute inside the chain.


public function passes($attribute, $value)
{
    return str_word_count($value) <= 500;
}

public function message()
{
    return 'The :attribute cannot be longer than 500 words.';
}

Step 3. Calling the rule from the query class

For validation I personally like to use Request classes, so in my app/Http/Requests/StoreCompanyRequest.php file, for example, I can use our new rule like this:


use App\Rules\MaxWordsRule;
use Illuminate\Foundation\Http\FormRequest;

class StoreCompanyRequest extends FormRequest
{

    public function rules()
    {
        return [
            'name'          => [
                'required',
            ],
            'description' => [
                new MaxWordsRule(),
            ]
        ];
    }
}

Also note that I like to use arrays of validation rules instead of a simple string like ‘name’ => ‘required’it’s a completely personal preference.

And there you have it, if we put a description of more than 500 words, we get an error: “The description cannot exceed 500 words”.


Step 4. Bonus: Make Words Count as a Parameter

Did you notice that our Rule class has an empty file generated __construction() method? This is exactly what we will use to pass a parameter to our rule. This way, you can choose to have 500 words maximum for one field, but only 100 words maximum for another field.

Changes in the Rule class:


class MaxWordsRule implements Rule
{

    private $max_words;

    /**
     * Create a new rule instance.
     * @param integer $max_words
     *
     * @return void
     */
    public function __construct($max_words = 500)
    {
        $this->max_words = $max_words;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return str_word_count($value) <= $this->max_words;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute cannot be longer than '.$this->max_words.' words.';
    }
}

As you can see we have created a private class property $max_words and set the value in the constructor. After that we can use the value as $this->max_words everywhere in the class.

Change in how we call the rule:


public function rules()
{
    return [
        'short_description' => [
            new MaxWordsRule(100),
        ]
        'description' => [
            new MaxWordsRule(), // defaults to 500
        ]
    ];
}



Technology

Another Tech Information

Similar Posts