我的下拉菜单中包含从数据库填充的选项。我还有一个名为other
value 的选项-1
下面是 html 输出以便更好地理解
这Other is hardcoded
。
我创建了一个请求验证文件和代码,如下所示。
<?php
namespace App\Http\Requests\Profiles\Form;
use Illuminate\Foundation\Http\FormRequest;
class BasicRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => 'required|min:3|max:30',
'relation' => 'required'
];
}
}
现在,如何编写验证条件来仅检查数据库中是否存在不等于 -1 的选项。
可以说,如果我使用exists:relations,name
对我自己来说工作正常...侄子,但会抛出 -1 错误。我不想将其他添加到数据库表中。
处理这个问题的一个简单方法是使规则动态化。
exists
当值不为-1 时,您可以添加规则。所以你的表单验证规则可能看起来像
确保为
Rule::in
.您也可以为此创建一个自定义验证规则...但这对于这样一个简单的场景来说似乎有点过分了。