Home > Software design >  Laravel custom rule's custom validation error message
Laravel custom rule's custom validation error message

Time:10-23

i have a custom rule which i made using rule objects and its working fine except for one thing, that it doesn't pick up the custom validation message i created for it in the component and instead picks whatever it is assigned to it in the validation.php file or the equivalent translation of it from the translated validation.php file. other non-custom rules are working as expected with the custom messages for the same field.

the component:

public function rules()
    {
        return[
            'topic' => ['required', 'string', 'max:250', 'min:5', new Profane],
            'name' => ['required', 'string', 'max:250'],
            'email' => ['required', 'email:rfc,dns', 'max:250']
        ];
    }

protected $messages = [
        'topic.required' => 'some message',
        'topic.max' => 'some message',
        'topic.min' => 'some message',
-->     'topic.profane' => 'some message',
        'name.required' => 'some message',
        'name.max' => 'some message.',
        'email.email' => 'some message',
        'email.required' => 'some message',
    ];

the rule object:

public function passes($attribute, $value)
    {
        $profane = ProfaneWord::all();
        $words = $profane->pluck('word');
        foreach ($words as $word)
        {
            if (stripos($value, $word) !== false) return false;
        }
        return true;
    }

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

CodePudding user response:

This does not currently seem possible when using custom rules. The problem in the source the message is only ever retrieved from the message() method. However since the validation rule is your own class you can always change it:

    private $message; 
    public __construct($message = null) {
       $this->message = $message;
    }

    public function passes($attribute, $value)
    {
        $profane = ProfaneWord::all();
        $words = $profane->pluck('word');
        foreach ($words as $word)
        {
            if (stripos($value, $word) !== false) return false;
        }
        return true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return $this->message??trans('validation.profane');
    }

  • Related