如何在 laravel 5 中提供自定义验证消息

how to give custom validation messages in laravel 5

我一直在关注 laravel 4.2,今天尝试了 laravel 5。

如何向 laravel 5 中的规则添加自定义验证消息。

代码示例

namespace App\Http\Requests;

 
use App\Http\Requests\Request;
 

class MyRequest extends Request {


    /**

     * Determine if the user is authorized to make this request.

     *

     * @return bool

     */

    public function authorize()

    {

        return true;

    }

 

    /**

     * Get the validation rules that apply to the request.

     *

     * @return array

     */

    public function rules()

    {

        return [

            'email' => 'required|email',

            'password' => 'required|min:8'

        ];

    }

}
// in your controller action
public function postLogin(\App\Http\Requests\MyRequest $request)

{

    // code here will not fire

    // if the validation rules

    // in the request fail

}

?>

和4.2一样不清楚

您可以从 messages() 方法中 return 它们,就像您使用规则一样:

public function messages(){
    return [
        'required' => 'The :attribute field is required.'
    ];
}

除了 messages() 方法,您还可以在 lang 文件 (resources/lang/[language]/validation.php) 中执行此操作,如果您想做的只是更改,例如关于一个唯一规则的消息您可以在整个应用程序中使用电子邮件字段:

/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/

'custom' => [
    'attribute-name' => [
        'rule-name' => 'custom-message',
    ],
    'email' => [
        'unique' => 'This email is already registered...etc',
    ]
],