【发布时间】:2017-10-21 08:21:06
【问题描述】:
我验证了一个模型
$validator = $c->validate($collection);
这是验证函数
public function validate($data){
return Validator::make($data, $this->rules());;
}
这些是规则
public function rules() {
return array([
'name' => [
'required', 'You need to choose a name for your collection.',
'unique:collections,table_name', 'A collection or collection table with this name already exists'
],
...
]);
}
我正在尝试发回带有验证器错误的 JSON 响应,例如:
return response()->json($validator->errors(), 200);
我目前正在测试“名称”规则的验证,但验证器失败了,正如预期的那样。
但是,我希望它返回该规则的消息(“具有此名称的集合或集合表已存在”)
相反,我将其返回:
我的目标是让 laravel 发回我需要的错误,提前感谢您的帮助。
编辑:更新代码:
消息:
public function messages(){
return [
'name.required' => 'A name must be specified for the collection',
'name.unique' => 'A collection or collection table with this name already exists',
'name.min' => 'The collection name is too short',
'fields.*.fieldName.unique' => 'Field names must be unique',
'fields.*.fieldName.required' => 'One or more fields must be specified for the collection',
'fields.*.fieldName.not_in' => 'Illegal field name, please try another one',
'fields.*.fieldName.min' => 'The field name is too short',
'fields.*.dataType.required' => 'A data-type must be specified for fields',
'fields.*.dataType.in' => 'Illegal data-type'
];
}
public function rules() {
return array([
'name' => [
'required', 'You need to choose a name for your collection.',
'unique:collections,table_name', 'A collection or collection table
with this name already exists',
'min:2'
],
'fields.*.fieldName' =>
[
'unique' => 'Please ensure that the fields are uniquely named.',
'required' => 'You must specify a name for your fields.',
'not_in:'.implode(',', self::$illegalFieldNames),
'min:2'
],
'fields.*.dataType' =>
[
'required', 'You must specify a data type for your fields.',
'in:'.implode(',', self::$allowedDataTypes)
]
]);
}
public function validate($data){
return Validator::make($data, $this->rules(), $this->messages());
}
【问题讨论】:
标签: json laravel validation response rules