我在Laravel 5.3中使用了二维数组字段。我希望根据需要验证其中的所有值,并显示各个错误消息。 我在控制器功能中使用了验证,如下所示
$this->validate($request, [
'training_id' =>'required',
'survey_name' =>'required',
'question.*' =>'required',
'answer_option.*.*' =>'required'
],
['question.*.required' => 'The question field is required.',
'answer_option.*.*.required' => 'The answer field is required.']);
在我尝试显示所有错误消息的视图页面中,只有第一行答案才会被验证,其他答案不会被证实。错误消息为
Array ( [0] => The question field is required. [1] => The question field is required. [2] => The answer_option.0.0 field is required. [3] => The answer_option.0.1 field is required. [4] => The answer_option.0.2 field is required. [5] => The answer_option.0.3 field is required. [6] => The training id field is required. [7] => The survey name field is required. )
答案 0 :(得分:0)
要分别使用自定义错误消息验证所有字段,手动创建验证器是最佳解决方案....
步骤1:
use Validator; (after namespace of any controller where validation is needed)
步骤2:
添加方法(假设方法名称为check_data())。在下面的代码中将放置....
public function check_data(Request $request){
//Rules for form fields
$rules = array(
'training_id' =>'required',
'survey_name' =>'required',
'question' =>'required',
'answer_option' =>'required'
);
//Custom message for individual fields
$messages = array(
'training_id.required' => 'Training Id should not be empty...',
'survey_name.required' => 'Survey Name is Essential...',
'question.required' => 'Question is urgent...',
'answer_option.required' => 'Answer option can be any one but required...'
);
$validator = Validator::make($request->all(), $rules, $messages);
//Check for validation
if ($validator->fails()) {
//if validation fails
return redirect()->back()->withInput()->withErrors($validator);
} else {
//Validation is successful and do as you wish
return "All data are validated !!";
}
}
希望,它会起作用