在 Laravel 中,你可以使用自定义值进行验证,这通常涉及到自定义验证规则或者使用 sometimes
验证规则来根据特定条件应用验证。以下是一些基础概念和相关信息:
自定义验证规则:允许你定义自己的验证逻辑,以满足特定的业务需求。
有时验证(Sometimes Validation):这个规则允许你在某些情况下应用验证规则,而在其他情况下忽略它们。
Illuminate\Contracts\Validation\Rule
接口。use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'custom_field' => [
Rule::requiredIf(function ($input) {
return $input->another_field === 'some_value';
}),
function ($attribute, $value, $fail) {
if ($value !== 'expected_custom_value') {
$fail('The :attribute must be "expected_custom_value".');
}
},
],
]);
if ($validator->fails()) {
return redirect('your-route')
->withErrors($validator)
->withInput();
}
// 继续处理请求...
}
首先,创建一个自定义规则类:
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class CustomValue implements Rule
{
protected $expectedValue;
public function __construct($expectedValue)
{
$this->expectedValue = $expectedValue;
}
public function passes($attribute, $value)
{
return $value === $this->expectedValue;
}
public function message()
{
return 'The :attribute must be "' . $this->expectedValue . '".';
}
}
然后,在控制器中使用这个规则:
use App\Rules\CustomValue;
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'custom_field' => ['required', new CustomValue('expected_custom_value')],
]);
if ($validator->fails()) {
return redirect('your-route')
->withErrors($validator)
->withInput();
}
// 继续处理请求...
}
如果你在使用自定义验证规则时遇到问题,比如规则没有被正确应用,可能的原因包括:
解决方法:
dd()
或日志记录来检查验证器的中间状态。通过以上步骤,你应该能够解决大多数与自定义验证规则相关的问题。
领取专属 10元无门槛券
手把手带您无忧上云