【问题标题】:Passing the value of current field to custom validation function in Laravel将当前字段的值传递给 Laravel 中的自定义验证函数
【发布时间】:2022-01-17 17:20:29
【问题描述】:

我想将当前字段的值传递给我的 Laravel 项目的 Request 类中的自定义验证函数。

我尝试了以下方法:

public function rules()
{
    return [
        'id'=>'required',
        //'type'=>'required|in:Attachment,Audio,Book,Picture,Video',
        'type'=>['required', $this->validateFileType()],
        //'type'=>[new Enum(FileType::class)], # only available on PHP 8.1+
        'soft_price' => 'numeric|min:1000',
        'hard_price' => 'numeric|min:1000',
    ];
}

public function validateFileType($type){

    $file_types = ['Attachment', 'Audio', 'Book', 'Picture', 'Video'];

    if(in_array($type, $file_types))
        return true;
    else
        return false;
}

我收到以下错误:

"Too few arguments to function App\\Http\\Requests\\FileUpdateRequest::validateFileType(), 0 passed in C:\\xampp\\htdocs..."

我该怎么做?

【问题讨论】:

    标签: php validation laravel-8


    【解决方案1】:

    你应该看看Custom Validation Rules

    您可以使用 artisan 添加自定义规则类:

    php artisan make:rule MyFileType
    

    在其中,您可以访问当前值并输出自定义错误消息

    public function passes($attribute, $value)
    {
        $file_types = ['Attachment', 'Audio', 'Book', 'Picture', 'Video'];
        
        if(in_array($value, $file_types))
            return true;
        else
            return false;
    }
    

    您可以像这样在代码中使用它:

    use App\Rules\MyFileType;
    
    public function rules()
    {
        return [
            ...
            'type' => ['required', new MyFileType],
            ...
        ];
    }
    

    【讨论】:

    • 谢谢,虽然我不得不:in_array($value, $file_types)
    • 对不起,我修好了。
    【解决方案2】:

    创建新规则:

    <?php
    
    namespace App\Rules;
    
    use Illuminate\Contracts\Validation\Rule;
    
    class FileTypeRule implements Rule
    {
        public function passes($attribute, $value)
        {
            $file_types = ['Attachment', 'Audio', 'Book', 'Picture', 'Video'];
    
            if(in_array($file_types, $value))
               return true;
            else
               return false;
        }
    }
    

    在请求规则方法中使用它:

    public function rules()
    {
        return [
            'id'=>'required',
            'type'=>['required', new FileTypeRule()],
            'soft_price' => 'numeric|min:1000',
            'hard_price' => 'numeric|min:1000',
        ];
    }
    

    【讨论】:

      【解决方案3】:

      您必须在规则函数中传递两个参数,有关更多信息,请查看laravel documentation

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        • 2018-01-12
        • 1970-01-01
        • 2014-03-23
        • 2015-11-22
        相关资源
        最近更新 更多