我正在尝试做一些laravel验证。
我需要确保字段最大租金总是比最低租金高,并且提供一条让用户知道的消息。
这是我的控制器中的验证码
$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",
]);
我没有使用单独的规则方法。这是在控制器内
答案 0 :(得分:2)
您可以使用Custom Validation Rule。
php artisan make:rule RentRule
应用\规则\ 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.';
}
}
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')],
]);
我建议你使用Form Request类从控制器中提取验证逻辑并解耦你的代码。这将使您拥有只具有一种责任感的类,从而使测试更容易,阅读更清晰。
答案 1 :(得分:-1)
$this->validate($request, [
"county" => "required",
"town" => "required",
"type" => "required",
"min-bedrooms" => "required",
"max-bedrooms" => "required",
"min-bathrooms" => "required",
"max-bathrooms" => "required",
"min-rent" => "required|numeric|max:9999",
"max-rent" => "required|numeric|min:min-rent|max:9999",
]);