Laravel验证.一个字段必须大于另一个字段 [英] Laravel validating. One field must be greater than another
问题描述
我正在尝试做一些Laravel验证.
I'm trying to do some laravel validation.
我需要确保字段最高租金"始终大于最低租金",并提供一条消息让用户知道.
I need to ensure that the field max rent is always great than min rent and to proivded a message letting the user know.
这是我的控制器中的验证码
Here is my validation code in my controller
$this->validate($request, [
"county" => "required",
"town" => "required",
"type" => "required",
"min-bedrooms" => "required",
"max-bedrooms" => "required",
"min-bathrooms" => "required",
"max-bathrooms" => "required",
"min-rent" => "required|max4",
"max-rent" => "required|max4",
]);
我没有使用单独的规则方法.这是在控制器内
I'm not using a seperate rules method. This is within the controller
推荐答案
您可以使用自定义验证规则.
php artisan make:rule RentRule
2.插入您的逻辑
App \ Rules \ RentRule
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class RentRule implements Rule
{
protected $min_rent;
/**
* Create a new rule instance.
*
* @param $min_rent
*/
public function __construct($min_rent)
{
// Here we are passing the min-rent value to use it in the validation.
$this->min_rent = $min_rent;
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
// This is where you define the condition to be checked.
return $value > $this->min_rent;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
// Customize the error message
return 'The maximum rent value must be greater than the minimum rent value.';
}
}
3.使用它
use App\Rules\RentRule;
// ...
$this->validate($request, [
"county" => "required",
"town" => "required",
"type" => "required",
"min-bedrooms" => "required",
"max-bedrooms" => "required",
"min-bathrooms" => "required",
"max-bathrooms" => "required",
"min-rent" => "required|max4",
"max-rent" => ["required", new RentRule($request->get('min-rent')],
]);
旁注
我建议您使用表单请求类来提取验证逻辑与控制器并解耦代码.这样一来,您就可以拥有只具有一种职责的类,从而使其更易于测试和阅读.
Side note
I suggest you to use Form Request classes to extract the validation logic from the controller and decouple your code. This will let you have classes that has just one responsability making it easier to test and cleaner to read.
这篇关于Laravel验证.一个字段必须大于另一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!