Laravel 验证自定义消息
Posted
技术标签:
【中文标题】Laravel 验证自定义消息【英文标题】:Laravel Validation custom message 【发布时间】:2014-05-31 19:56:43 【问题描述】:我遇到了 laravel 自定义验证消息的问题,这是我所拥有的:
$rules = [
'first_name' => 'required|alpha|min:2',
'last_name' => 'required|alpha|min:2',
'email' => 'required|email|unique:users,email,' . Input::get('id') . ',id',
'password' => 'alpha_num|between:6,12|confirmed',
'password_confirmation' => 'alpha_num|between:6,12',
'address' => 'regex:/^[a-z0-9- ]+$/i|min:2',
'city' => 'alpha|min:2',
'state' => 'alpha|min:2|max:2',
'zip' => 'numeric|min:5|max:5',
'phone' => 'regex:/^\d3\-\d3\-\d4$/',
];
$messages = [
'unique' => 'The :attribute already been registered.',
'regex' => 'The :attribute number has to be formated : xxx-xxx-xxxx.',
];
现在如果地址或电话号码有问题,因为两者都有正则表达式验证规则,错误消息将是::属性号码必须格式化:xxx-xxx-xxxx,我怎么能有自定义消息每个不同的??
【问题讨论】:
How to specify the default error message when extending the Validation class in Laravel 4的可能重复 其实我现在刚刚解决了,:) 你只需要这个 如果您解决了这个问题,请回答您的问题以造福未来的 SO 用户。 $messages = array( 'unique' => ':attribute 已注册。','phone.regex' => ':attribute 编号无效,接受格式:xxx-xxx- xxxx','address.regex' => ':attribute 格式无效',); 'fieldname.unique' 或 'fieldname.regex' 【参考方案1】:这里是这样做的方法,而不是使用 'regex' ,使用 'phone.regex'
$rules = [
'first_name' => 'required|alpha|min:2',
'last_name' => 'required|alpha|min:2',
'email' => 'required|email|unique:users,email,' . Input::get('id') . ',id',
'password' => 'alpha_num|between:6,12|confirmed',
'password_confirmation' => 'alpha_num|between:6,12',
'address' => 'regex:/^[a-z0-9- ]+$/i|min:2',
'city' => 'alpha|min:2',
'state' => 'alpha|min:2|max:2',
'zip' => 'numeric|min:5|max:5',
'phone' => 'regex:/^\d3\-\d3\-\d4$/',
];
$messages = [
'unique' => 'The :attribute already been registered.',
'phone.regex' => 'The :attribute number is invalid , accepted format: xxx-xxx-xxxx',
'address.regex' => 'The :attribute format is invalid.',
];
【讨论】:
直到今天才知道 :) 我还删除了一个额外的数组关闭 - 语法错误 :)以上是关于Laravel 验证自定义消息的主要内容,如果未能解决你的问题,请参考以下文章