我决定创建一个名为 without:field1,field2 的新规则:
Validator::extend('without', function($attribute, $value, $parameters, \Illuminate\Validation\Validator $validator) {
foreach($parameters as $compare) {
// Check if the given parameters are filled in, if so we return `false`.
if($validator->validateRequired(null, array_get($validator->getData(), $compare))) {
return false;
}
}
// No `without` parameters have been found, validation successful.
return true;
});
// Replace the error message placeholders.
Validator::replacer('without', function ($message, $attribute, $rule, $parameters, \Illuminate\Validation\Validator $validator) {
$attributes = [];
foreach ($parameters as $key => $value) {
$attributes[$key] = $validator->getDisplayableAttribute($value);
}
return str_replace(':values', implode(' / ', $attributes), $message);
});
接下来,给resources/lang/en/validation.php添加翻译:
'without' => 'The :attribute may not be set with :values',
那么你可以像这样简单地使用它:
$this->validate($request, [
'points' => 'nullable|without:coupon',
'coupon' => 'nullable|without:points'
]);
(您可以添加多个参数,如without:coupon,user_id)
确保:
- 同时传递
points 和 coupon 会导致验证错误
- 通过其中一个就可以了
- 两者都不能通过