简体   繁体   English

可选字段的 Laravel 验证

[英]Laravel validation of optional fields

I currently have a few validation rules as follows:我目前有一些验证规则如下:

\Route::post("/logError", "LogController@logError");

 //In LogController
 public function logError(Request $request) { 
    $rules = [
        "name" => "required", 
        "message" => "required",
        "level" => "in:info,debug,error"
    ];

    $this->validate($request,$rules);
    // Log the message or do whatever
});

This works fine for inputs like这适用于像这样的输入

[ "name"=>"Not found", "message" => "Element not found", "level" => "error" ]
[ "name"=>"Not found", "message" => "Element not found" ]` 

However it throws an exception for inputs like但是,它会为输入引发异常,例如

[ "name"=>"Not found", "message" => "Element not found", "level" => "randomgibberish" ]

My question is, since "level" is optional, is there a built-in way to validate the input and just remove optional elements that are not valid from it instead of throwing a validation exception?我的问题是,由于“级别”是可选的,是否有一种内置方法来验证输入并仅删除无效的可选元素而不是抛出验证异常? If not would I have to override the controller validation method to achieve this?如果不是,我是否必须覆盖控制器验证方法才能实现这一点?

The validator does not modify the request input data, you need to make some sort of middleware or function in your controller that checks for the input parameters and compares them with the ones you want Laravel to check.验证器不会修改请求输入数据,您需要在控制器中创建某种中间件或函数来检查输入参数并将它们与您希望 Laravel 检查的参数进行比较。

So yes, I think you'll need to extend the validation method, or maybe try with an helper function that does only that.所以是的,我认为您需要扩展验证方法,或者尝试使用仅执行此操作的辅助函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM