让我先展示一下我的代码。这是我的控制器功能代码
public function save(Request $request) {
try {
$this->validate($request, Venue::rules()); // Validation Rules
$venue = Venue::saveOrUpdate($request);
if($venue !== false) {
if($request->get('continue', false)) {
return redirect()->route('admin.venue.edit', ['id' => $venue->id])->with('success', trans('admin.venue.save_success'));
} else {
return redirect()->route('admin.venue.index')->with('success', trans('admin.venue.save_success'));
}
} else {
return back()->with('error', "Unable to save venue")->withInput();
}
} catch (\Exception $ex) {
return back()->with('error', "Unable to save venue")->withInput();
}
}
这是我的模型功能代码
public static function rules($id = '') {
return [
'name' => 'required|string|max:255',
'logo' => 'required',
'status' => 'required|string|in:' . implode(",", Venue::STATUSES),
'venue_type_id' => 'required|string|not_in:0',
'client_id' => 'required|string|not_in:0',
];
}
所以现在我提交表单验证时显示消息。我想改变这个消息。我怎么能这样做。
您可以通过覆盖error messages
方法来自定义form request
使用的messages()
。在messages
课程中添加自定义Venue
如下 -
public static function messages($id = '') {
return [
'name.required' => 'You must enter your name',
'logo.required' => 'You must upload logo',
'key.rules' => 'your messages'
];
在您的控制器上添加messages
作为第三个parameter
像 -
$this->validate($request, Venue::rules(), Venue::messages());
这就是我这样做的方式,可以作为指导。从您的表单中,您基本上有4个输入字段,并假设它们被命名为name,client,logo和venue_type。控制器中验证表单请求的函数如下所示: N.B - 你应该把 - 使用Validator;使用Illuminate \ Http \ Request; - 在班级的顶部
public function validateFormRequest($request){ try { //specify your custom message here $messages = [ 'required' => 'The :attribute field is required', 'string' => 'The :attribute must be text format', 'file' => 'The :attribute must be a file', 'mimes' => 'Supported file format for :attribute are :mimes', 'max' => 'The :attribute must have a maximum length of :max', ]; $validator = Validator::make($request->all(), [ 'name' => 'required|string|max:75', 'client' => 'required|string|max:75', 'logo' => 'required|file|mimes:jpeg,png,jpg,gif', 'venue_type' => 'required|string', ], $messages); if($validator->fails()){ // Validation Failed..log errors or Return Errors to view/blade } else{ // Validation passed..Return true or positive info. i.e request can be saved } }catch (Exception $ex){ //Log your errors or return some error message to your view/blade } }
你可以添加这样的自定义错误。
$validation->errors()->add('error_input', 'error text');
return redirect()->back()->withInput()->withErrors($validation);
要么
return redirect()->back()->withInput()->withErrors(['error_input'=> 'error text');
您可以自定义验证消息,
去resources->lang->en->validation.php
在这里你看,
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
根据您的需要编辑它们。