laravel - Laravel 验证 - 三个中的一个必须是真的吗?
问题描述
我正在研究如何以一种不丑陋的方式做到这一点。
['input1'=>true, 'input2'=>false, 'input3'=> false] // valid
['input1'=>false, 'input2'=>false, 'input3'=> false] // not valid
['input1'=>null, 'input2'=>true, 'input3'=> false] // not valid
['input1'=>true, 'input2'=>true, 'input3'=> false] // not valid
这似乎真的很简单 - 只有当一个选项为true时,输入才有效,而另一个选项是false(不是null)。
谁能帮我做到这一点?
(Laravel 5.7 仅供参考)
解决方案
最终解决了。
我需要在表单请求中覆盖 getValidatorInstance 方法:
/**
* Override the validator instance
*/
protected function getValidatorInstance()
{
return parent::getValidatorInstance()->after(function ($validator) {
$trueAttributes =
collect(request()->only('input1','input2','input3'))
->reject(function($attribute){
return ($attribute !== true);
});
if ($trueAttributes->count() !== 1) {
$validator->errors()->add('data', 'At least one attribute must be true');
}
});
}
推荐阅读
- c++ - 如何获取指针数组中的元素数量?
- android - createWebPrintJob 不工作
- elasticsearch - Logstash 输入和输出字段
- python - 如何将未知维度的张量转换为 numpy 数组
- smtp - Jira 不使用 SMTP 密码
- python - 为什么我在 python subplot 中的绘图大小不同?
- python-3.x - 如何知道页面是否离线或没有响应?
- javascript - 检查对方是否重定向到登录页面
- python - 使用 Django 进行电子邮件编码
- java - 由 JsonItemReaderBuilder 构建的单元测试阅读器