我有一个选择列表,其中第一个选项被禁用,这样,当用户未选择有效选项时,选择列表的结果将不在请求中。
在验证中,如果其他字段的值例如为1, in case not 1, the field is not required
,则该字段为必填字段。
代码:
'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');
}
}
答案 0 :(得分:0)
尝试一下:
'city_id' => [
'nullable',
'numeric',
Rule::in(City::availableCities())
],
'district_id' => new DistrictValidation(request('city_id')),
答案 1 :(得分:0)
尝试:
$myValidations = [
"city_id" => [
"required",
"integer"
]
]
// if city_id exists in availableCities so add some rules
if(collect(city::availableCities)->contains(request("city_id"))){
$myValidations["district_id"] = new DistrictValidation(request('city_id'))
}
// validate request fields with $myValidations variable
答案 2 :(得分:0)
尝试使用required_if
验证,在其中必须存在要验证的字段,并且如果anotherfield字段等于任何值,则该字段不能为空。
required_if:field,value,...
使用方式:
$request->validate([
'city_id' => 'required|integer|Rule::in(City::availableCities())',
'district_id' => 'required_if:city_id,1',
]);
尝试阅读更多的laravel验证here
答案 3 :(得分:0)
您可以使用laravel验证中定义的averageNum = data.iloc[:, 3:4].squeeze().mean()
print(averageNum)
9.0
条件
这是正确的文档https://github.com/gpac/gpac/issues
-cues