gpt4 book ai didi

php - Laravel 验证 : rules in required_if

转载 作者:行者123 更新时间:2023-12-04 15:53:34 28 4
gpt4 key购买 nike

我有一个选择列表,其中第一个选项被禁用,这样当用户没有选择有效选项时,选择列表的结果将不会在请求中。

在验证中,必填字段,如果其他字段的值为例如:1,如果不是1,则不需要该字段

代码:

'city_id' => [
'required',
'integer',
Rule::in(City::availableCities()),
],
'district_id' => new DistrictValidation(request('city_id')),

我该怎么做,district_id 每次都会抛出验证,无论它是否在请求中。

感谢您的回答,

更新:也许你看清楚了,如果 DistrictValidation 规则在这里:

class DistrictValidation implements Rule
{
protected $city;
private $messages;

/**
* Create a new rule instance.
*
* @param $cityId
*/
public function __construct($cityId)
{
$this->city = City::find($cityId);
}

/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
dd('here');
if (!$this->city) {
return false;
}

if (!$this->city->hasDistrict) {
return true;
}

$validator = Validator::make([$attribute => $value], [
$attribute => [
'required',
'integer',
Rule::in(District::availableDistricts()),
]
]);

$this->messages = $validator->messages();

return $validator->passes();
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return optional($this->messages)->first('district_id');
}
}

最佳答案

您可以使用在 laravel 验证中定义的 required_if 条件这是正确文档的链接 Laravel Validation

Validator::make($data, [
'city_id' => [
'required',
'integer',
Rule::in(City::availableCities()),
],
'district_id'=>[
'required_with:city_id,',
]
]);

关于php - Laravel 验证 : rules in required_if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52848375/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com