如何在 Laravel 中创建自定义排除验证规则
How to create a custom exclude validation rule in Laravel
我想创建一个在某些情况下排除属性的自定义规则,我能想到的唯一方法是:
- 手动验证 FormRequest 中的条件并添加 'exclude' 规则,如果我的条件是真的(即,imo,不太优雅)
- (我不确定这是否有效/不会有副作用)创建一个自定义验证规则,如果条件是是的。
有没有更好的方法来做到这一点?
我也找不到任何排除规则的实现。
这是一个模糊的答案来匹配你模糊的问题,但是在应用规则之前使用 conditional complex validation. Use the withValidator()
method 访问验证器实例很容易做到。
// assuming we're inside a FormRequest
public function withValidator($validator)
{
$validator->sometimes(
'some_field',
'required|string|max64',
fn ($data) => $data->some_other_field !== 1234
);
}
sometimes()
的第一个参数是您要有条件地验证的字段;第二个是您要应用的规则;第三个是回调。回调传递请求数据;如果 returns 为真,将应用规则。
有很多方法可以根据条件排除验证规则。
您可以使用 exclude_if
、exclude_unless
和 exclude_without
。
假设你想排除一个字段验证,如果它的另一个字段的值为空,那么你可以使用
['field1' => 'exclude_if:field2,null|<validation rules for field1>']
再次假设您要排除一个字段验证,除非另一个值不等于 3,然后使用,
['field1' => 'exclude_unless:field2,==,3|<validation rules for field1>']
我刚刚发现,由于 Laravel 8.55 规则对象中有方法 'when',您可以在 rules() 方法中使用它来排除属性:
Rule::when(MyCallBackThatReturnsABoolean, [/*RulesIfCallBackReturnsTrue*/], [/*RulesIfCallBackReturnsFalse*/])
由于某些原因,我在文档中找不到该方法。
例如,如果条件 foo==bar 为假,则排除属性我可以这样做:
Rule::when(function() use(foo,bar) { return foo===bar }, ['required', 'string'], ['exclude'])
拉取请求 here and here
Example of usage here
我想创建一个在某些情况下排除属性的自定义规则,我能想到的唯一方法是:
- 手动验证 FormRequest 中的条件并添加 'exclude' 规则,如果我的条件是真的(即,imo,不太优雅)
- (我不确定这是否有效/不会有副作用)创建一个自定义验证规则,如果条件是是的。
有没有更好的方法来做到这一点?
我也找不到任何排除规则的实现。
这是一个模糊的答案来匹配你模糊的问题,但是在应用规则之前使用 conditional complex validation. Use the withValidator()
method 访问验证器实例很容易做到。
// assuming we're inside a FormRequest
public function withValidator($validator)
{
$validator->sometimes(
'some_field',
'required|string|max64',
fn ($data) => $data->some_other_field !== 1234
);
}
sometimes()
的第一个参数是您要有条件地验证的字段;第二个是您要应用的规则;第三个是回调。回调传递请求数据;如果 returns 为真,将应用规则。
有很多方法可以根据条件排除验证规则。
您可以使用 exclude_if
、exclude_unless
和 exclude_without
。
假设你想排除一个字段验证,如果它的另一个字段的值为空,那么你可以使用
['field1' => 'exclude_if:field2,null|<validation rules for field1>']
再次假设您要排除一个字段验证,除非另一个值不等于 3,然后使用,
['field1' => 'exclude_unless:field2,==,3|<validation rules for field1>']
我刚刚发现,由于 Laravel 8.55 规则对象中有方法 'when',您可以在 rules() 方法中使用它来排除属性:
Rule::when(MyCallBackThatReturnsABoolean, [/*RulesIfCallBackReturnsTrue*/], [/*RulesIfCallBackReturnsFalse*/])
由于某些原因,我在文档中找不到该方法。
例如,如果条件 foo==bar 为假,则排除属性我可以这样做:
Rule::when(function() use(foo,bar) { return foo===bar }, ['required', 'string'], ['exclude'])
拉取请求 here and here
Example of usage here