[英]Laravel 5.7: Custom attributes for form validation not working
我想同时使用自定义消息和属性来验证表单。 代替name: The name may not be greater than 20 characters.
用户应该看到Name: Please use fewer characters.
, 例如。
我正在使用AJAX以及Laravel返回的response.data.errors
对象的键和值。 我正在使用Laravel 5.7。
这是我RegisterController
validator
功能的简化版本。
protected function validator(array $data)
{
// Nice attribute names
$attributes = [
'name' => 'Name',
// ...
];
// Custom messages
$messages = [
'max' => 'Please use fewer characters.'
// ...
];
// Rules
$rules = [
'name'=> 'required|max:20',
// ...
];
// Working for messages, but not for attribute names
$validator = Validator::make($data, $rules, $messages, $attributes);
// Also not working
// $validator->setAttributeNames($attributes);
return $validator;
}
发生验证错误时,用户会收到一条消息,如name: Please use fewer characters.
。 这意味着将显示来自我的自定义数组的消息,但使用默认属性名称。 怎么了
属性不会替换键名,它们用于更改消息中键的外观(即The Name field is required
,以实现您要在问题中尝试做的事情,您需要创建一个新的数据数组。
protected function validator(array $data)
{
$data = [
'Name' => $data['name'] ?? '',
// ...
];
// ...
Validator::make($data, $rules, $messages);
}
这来自resources / Lang / xx /中的validation.php。
编辑:
您必须使用
$messages = [ 'name.max' => 'Your sentence here', ];
您必须向所有验证规则发送消息。
// Custom messages
$messages = [
'name.required' => 'The name field is required',
'name.max:20' => 'Please use less characters.'
// ...
];
使用Laravel表单请求 ,向下滚动到“ Customizing The Error Messages
部分。 查看以下示例代码。
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UserRegistrationForm extends FormRequest
{
/**
* 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 [
'name' => 'required|max:20',
];
}
/**
* Get the error messages for the defined validation rules.
*
* @return array
*/
public function messages()
{
return [
'name.max' => 'Please use less characters'
];
}
}
在控制器中
public function register(UserRegistrationForm $request)
{
// do saving here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.