Laravel:验证器仅验证传递数据中存在的字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21070281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:42:41  来源:igfitidea点击:

Laravel: Validator to validate only fields which exist in the passed data?

validationlaravel

提问by barakuda28

Currently the Validator will fail if I have a required rule for a key "name", but I haven't passed it in the data array. I want it not to fail in this case. I want to validate only the fields which exist in the data array. Is there a builtin way for that to happen, or I have to extend the Validator class?

目前,如果我有一个键“名称”的必需规则,验证器将失败,但我没有在数据数组中传递它。我希望它在这种情况下不会失败。我只想验证数据数组中存在的字段。是否有内置方法可以实现,或者我必须扩展 Validator 类?

回答by Holger Weis

You can use the sometimesvalidation rule.

您可以使用sometimes验证规则。

In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list.

在某些情况下,您可能希望仅当输入数组中存在该字段时才对该字段运行验证检查。要快速完成此操作,请将有时规则添加到您的规则列表中。

http://laravel.com/docs/validation#conditionally-adding-rules

http://laravel.com/docs/validation#conditionally-adding-rules

$v = Validator::make($data, array(
    'email' => 'sometimes|required|email',
));

Be sure to run composer updatesince the sometimes shortcut is a Laravel 4.1.14 feature.

一定要运行,composer update因为有时快捷方式是 Laravel 4.1.14 的功能。

https://twitter.com/laravelphp/status/422463139293057024

https://twitter.com/laravelphp/status/422463139293057024

回答by Eduardo Aguad

You can use nullable and it will pass if email is not present

您可以使用 nullable,如果电子邮件不存在,它将通过

$request->validate([
    'name' => 'required',
    'email' => 'nullable|email'
])

Also, you should remove requiredvalidation.

此外,您应该删除required验证。

回答by Calvin

For Laravel version less then 5.9

对于低于 5.9 的 Laravel 版本

For anyone, having the validator object, using:

对于拥有验证器对象的任何人,使用:

Method ->validateFilled(string $attribute, mixed $value)

Method ->validateFilled(string $attribute, mixed $value)

may also help them to validate the given attribute is filled if it is present. May help someone in their respective case.

也可以帮助他们验证给定的属性是否存在。可能会在他们各自的情况下帮助某人。

Source:- https://laravel.com/api/5.8/Illuminate/Validation/Validator.html#method_validateFilled

来源:- https://laravel.com/api/5.8/Illuminate/Validation/Validator.html#method_validateFilled