1
votes

I have created a custom validation rule and I am using it to validate a data field in a FormRequest.

However, I would like to use a different message for this field and not the default message that is set in the Rule's message() method.

So, I tried using the method messages() inside of the FormRequest using a key of the field name and the rule (in snake case)

public function rules()
{
    return [
        'clients' => [
            new ClientArrayRule(),
        ],
    ];
}

public function messages()
{
    return [
        'clients.client_array_rule' => "clients should be a valid client array"
    ];
}

The error message did not change, I investigated a little inside the code of the validator and I found out that for custom rules, it uses the method validateUsingCustomRule that doesn't seem to care about custom messages.

Any ideas on how it can be overwritten or what would be the best way to do it?

1
Can you show us the content of your rules() method? - Denis Priebe
@DenisPriebe I edited the question adding rules method - Alaa Saleh

1 Answers

1
votes

For custom message on Laravel:

 /**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'username' => 'required',
        'password' => 'required',
        'email' => 'required',
        'age' => 'required|gte:4',

    ];
}


/**
 * Get the error messages for the defined validation rules.
 *
 * @return array
 */
public function messages()
{
    return [
        'username.required' => 'Custom message',
        'password.required' => 'Custom message',
        'email.required' => 'Custom message',
        'age.required' => 'Custom message',
        'age.gte' => 'Custom message'
    ];
}