Laravel:验证需要大于另一个的整数字段 [英] Laravel: validate an integer field that needs to be greater than another
问题描述
我有两个字段,仅当两个字段都不存在时才是可选的:
I have two fields that are optional only if both aren't present:
$rules = [
'initial_page' => 'required_with:end_page|integer|min:1|digits_between: 1,5',
'end_page' => 'required_with:initial_page|integer|min:2|digits_between:1,5'
];
现在,end_page
必须大于initial_page
.如何包含此过滤器?
Now, end_page
needs to be greater than initial_page
. How include this filter?
推荐答案
没有没有内置验证,可以让您比较 Laravel 中的字段值,因此您需要实现一个自定义验证器,以便您在需要时重复使用验证.幸运的是,Laravel使编写自定义验证程序变得非常简单.
There is no built-in validation that would let you compare field values like that in Laravel, so you'll need to implement a custom validator, that will let you reuse validation where needed. Luckily, Laravel makes writing custom validator really easy.
首先在 AppServiceProvider 中定义新的验证器:
Start with defining new validator in yor AppServiceProvider:
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Validator::extend('greater_than_field', function($attribute, $value, $parameters, $validator) {
$min_field = $parameters[0];
$data = $validator->getData();
$min_value = $data[$min_field];
return $value > $min_value;
});
Validator::replacer('greater_than_field', function($message, $attribute, $rule, $parameters) {
return str_replace(':field', $parameters[0], $message);
});
}
}
现在,您可以在 $规则中使用全新的验证规则:
Now you can use your brand new validation rule in your $rules:
$rules = [
'initial_page' => 'required_with:end_page|integer|min:1|digits_between: 1,5',
'end_page' => 'required_with:initial_page|integer|greater_than_field:initial_page|digits_between:1,5'
];
您将在此处找到有关创建自定义验证器的更多信息: http://laravel.com/docs /5.1/validation#custom-validation-rules .它们易于定义,可在您验证数据的任何地方使用.
You'll find more info about creating custom validators here: http://laravel.com/docs/5.1/validation#custom-validation-rules. They are easy to define and can then be used everywhere you validate your data.
这篇关于Laravel:验证需要大于另一个的整数字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!