Laravel验证错误消息required_if无效

时间:2016-03-15 23:43:20

标签: php laravel laravel-5.2 laravel-validation

我正在使用Laravel 5.2验证表单

使用验证检查required_if输入youtube-embed。验证成功发生但自定义错误消息不起作用。这是代码可能有人可以看看。

$messages = [
        'youtube-embed.required_if' => 'Please paste in your youtube embed code',
    ];

$this->validate($request, [
        'youtube-embed'      => 'required_if:youtube,on',
    ]);

这是laravel返回的错误消息,而不是我的自定义错误:

The youtube-embed field is required when youtube is on.

3 个答案:

答案 0 :(得分:3)

试试这个:

$this->validate($request, 
    ['youtube-embed'      => 'required_if:youtube,on',], 
    ['required_if' => 'Please paste in your youtube embed code',]
);

基本上,您可以将自定义消息作为验证功能中的第三个参数传递。

答案 1 :(得分:1)

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    $rules = [
        'payout_method' => 'required:in,bankTransfer,paypal',
        'paypal_email'  => 'required_if:payment_type,paypal|email',
        'receiver'      => 'required_if:payment_type,bankTransfer|max:45',
        'iban'          => 'required_if:payment_type,bankTransfer|max:45|iban',
        'bic'           => 'required_if:payment_type,bankTransfer|max:15|bic',
    ];

    return $rules;
}

/**
 * Get the error messages for the defined validation rules.
 *
 * @return array
 */
public function messages()
{
    return [
        'payout_method.required'   => trans('validation.attributes.payout_type_required'),
        'paypal_email.required_if' => trans('validation.attributes.paypal_email_required'),
        'paypal_email.email'       => trans('validation.attributes.paypal_email_invalid'),
        'iban.required_if'         => trans('validation.attributes.bank_account_required'),
        'bic.required_if'          => trans('validation.attributes.bank_swift_required'),
        'iban.iban'                => trans('validation.attributes.bank_account_invalid'),
        'bic.bic'                  => trans('validation.attributes.bank_swift_invalid'),
    ];
}

在这种情况下我能做些什么? Laravel返回' paypal电子邮件字段是必需的。'对于其他领域的这项工作,只能用于required_if

答案 2 :(得分:0)

如果您使用 Request 类:

public function messages()
{
    return [
        'youtube-embed.required' => 'Your custom message here.',
    ];
}

适用于 Laravel 7