仅当另一个输入也存在并设置为特定值时,才对特定输入应用特定验证规则

Apply a particular validation rule on a specific input, only if another input is also present and set to a specific value

简而言之,我想做的是检查数据库中特定输入 exists 的值,但我希望仅在另一个输入时才应用 exists 规则输入也具有特定值。

例如,假设我有一个表单,其中包含一个名为 type 的 select 和一个名为 id.

的文本字段
<select name="type">
    <option value="0">Type0</option>
    <option value="1">Type1</option>
</select>

<input type="text" name="id">

如果 type 存在并等于 1 我想检查 id 在数据库中输入 exists table users,否则根本不应用 exists 规则,而正常应用其余验证规则。

编辑:

我最好使用表单请求来进行验证。可以使用表单请求来实现吗?

您可以conditionally添加规则为:

$v = Validator::make(...);

$v->sometimes('id', 'exists:table,column', function($input) {
     return $input->get('type') == 1;
});

更新

对于 form request 你可以这样做:

$rules = [
    ...,
];

if ($this->get('type') == 1){
    if (isset($rules['id'])){
        $rules['id'] .= '|exists:table,column';
    }
    else {
        $rules['id'] = 'exists:table,column';
    }
}

return $rules;