如何在自定义验证规则的通过功能中发送多个参数 [英] How to send Multiple parameters in passes function of custom validation rule

查看:61
本文介绍了如何在自定义验证规则的通过功能中发送多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个自定义验证规则,该规则应该在自定义验证规则的pass函数中采用另一个带有属性和值的参数.当我们在编写自定义验证时实现Rule接口时,它不允许我们在passs函数中添加第三个参数,但是我需要第三个参数.而且,如果有人可以指导我有关将数据库包括在规则中的最佳实践,我将感到高兴.如果我们需要在定制验证规则中使用表,则应该在规则中仅包括所需的模型,或者在验证规则中编写查询时使用Illuminate \ Support \ Facades \ DB.我想要以下格式的通行证功能

I am implementing a custom validation rule which should take another parameter with attribute and value in passes function of custom validation rule. As we implement Rule interface while writing custom validations, it does not allow us to add third parameter in passes function but I need third parameter. Moreover, I will feel happy if anyone can guide me about the best practice of including database in rule. Either we should include only desired model in rule if we need a table in custom validation rule or we should use Illuminate\Support\Facades\DB while writing queries in validation rules. I want the following format of passes function

public function passes($attribute, $value,$extraparam)
{
    /*Code here*/
}

推荐答案

您可以将额外的参数作为参数传递给规则的构造函数

You could pass the extra parameter as an argument to the Rule's constructor

use App\Rules\Uppercase;

$request->validate([
    'name' => ['required', new Uppercase($param)],
]);

因此您可以将Rule的类修改为

so you could modify your Rule's class as

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Uppercase implements Rule
{
    protected $extraParam;

    public function __construct($param)
    {
        $this->extraParam = $param;
    }

    public function passes($attribute, $value)
    {
        // Access the extra param as $this->extraParam
        return strtoupper($value) === $value;
    }
}

这篇关于如何在自定义验证规则的通过功能中发送多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆