如果使用 Laravel 中的路由完成 CRUD 操作,如何添加验证
How to add validation if CRUD operation is done with routes in Laravel
如果使用路由而不是控制器,我想请您帮助我如何向表单添加验证。我目前使用的代码:
Route::post('/contact/submit', function (Request $request) {
validate($request,[
'FirstName'=>'required',
'LastName'=>'required',
'Age'=>'required'
]);
此外,如何添加自定义验证,例如,确保显示 "Please fill name field".
而不是消息 "Name is required"
是的,您需要使用 Validator
class 是的,您还可以为自定义消息添加另一个变量。
Route::post('/contact/submit', function (Illuminate\Http\Request $request) {
$rules = [
'FirstName' => 'required',
'LastName' => 'required',
];
$messages = [
"FirstName.required" => "First name is compulsory.",
"LastName.required" => "Last name is mandadory.",
];
$validator = Validator::make($request->all(), $rules,$messages);
if($validator->fails()){
return dd($validator->messages());
}
});
错误信息类似于
MessageBag {#1332 ▼
#messages: array:2 [▼
"FirstName" => array:1 [▼
0 => "First name is compulsory."
]
"LastName" => array:1 [▼
0 => "Last name is mandadory."
]
]
#format: ":message"
}
如果使用路由而不是控制器,我想请您帮助我如何向表单添加验证。我目前使用的代码:
Route::post('/contact/submit', function (Request $request) {
validate($request,[
'FirstName'=>'required',
'LastName'=>'required',
'Age'=>'required'
]);
此外,如何添加自定义验证,例如,确保显示 "Please fill name field".
而不是消息 "Name is required"是的,您需要使用 Validator
class 是的,您还可以为自定义消息添加另一个变量。
Route::post('/contact/submit', function (Illuminate\Http\Request $request) {
$rules = [
'FirstName' => 'required',
'LastName' => 'required',
];
$messages = [
"FirstName.required" => "First name is compulsory.",
"LastName.required" => "Last name is mandadory.",
];
$validator = Validator::make($request->all(), $rules,$messages);
if($validator->fails()){
return dd($validator->messages());
}
});
错误信息类似于
MessageBag {#1332 ▼
#messages: array:2 [▼
"FirstName" => array:1 [▼
0 => "First name is compulsory."
]
"LastName" => array:1 [▼
0 => "Last name is mandadory."
]
]
#format: ":message"
}