jesse_orange_newable
7 months ago

Using Validation Rule objects

Posted 7 months ago by jesse_orange_newable

I created a new Rule class called MinWords that checks whether an attribute contains x amount of words.

It looks like this:


<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class MinWords implements Rule
{
    /**
     * The minimum words that should be entered.
     *
     * @var int
     */
    public $min_words;

    /**
     * Create a new rule instance
     *
     * @param int $max_words
     */
    public function __construct($min_words = 25)
    {
        $this->min_words = $min_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->min_words;
    }

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



In this video: https://laracasts.com/series/lets-build-a-forum-with-laravel/episodes/53

It is shown that you can extend the validator using a class like I've done below:


/**
 * Extend the validator to include a min:words rule
 */
Validator::extend('min_words', 'App\Rules\[email protected]');


But how do you pass the attribute in the constructor to the translation file?

Please sign in or create an account to participate in this conversation.