使用带有附加参数的自定义规则在Laravel中验证数组 [英] Validating array in Laravel using custom rule with additional parameter

查看:92
本文介绍了使用带有附加参数的自定义规则在Laravel中验证数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel 5.7,我需要使用2个输入(前缀+数字)来验证电话长度.总位数必须始终为10.

I'm working with Laravel 5.7 and I need to validate a phone length by using 2 inputs (prefix+number). The total digits has to be 10 always.

我正在将此自定义规则用于其他效果很好的项目:

I'm using this custom rule for other projects which works fine:

<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;

class PhoneLength implements Rule
{
    public $prefix;

/**
 * Create a new rule instance.
 *
 * @return void
 */
public function __construct($prefix = null)
{
    //
    $this->prefix = $prefix;
}

/**
 * Determine if the validation rule passes.
 *
 * @param  string  $attribute
 * @param  mixed  $value
 * @return bool
 */
public function passes($attribute, $value)
{
    //
    return strlen($this->prefix)+strlen($value) == 10 ? true : false;
}

/**
 * Get the validation error message.
 *
 * @return string
 */
public function message()
{
    return 'El Teléfono debe contener 10 dígitos (prefijo + número)';
}
}

在我的控制器中,我做类似

In my controller I do something like

$validatedData = $request->validate([
  'prefix' => 'integer|required',
  'number' => ['integer','required', new PhoneLength($request->prefix)],
]);

现在我需要使用数组,所以我的新验证看起来像

Now I need to make use of arrays, so my new validation looks like

$validatedData = $request->validate([
  'phones.*.prefix' => 'required',
  'phones.*.number' => ['required', new PhoneLength('phones.*.prefix')],
]);

上面的代码根本不起作用,该参数未按预期发送. 如何发送数组值?当然,我需要从同一数组元素中获取值,因此,如果phones[0].number正在验证中,则需要前缀phones[0].prefix.

The above code doesn't work at all, the parameter is not being sent as expected. How can I send an array value? Of course I need to get the values from the same array element, so if phones[0].number is under validation, the prefix phones[0].prefix is needed.

我找到了这个问题,但是我拒绝相信这不可能以本机"的方式做到: 使用自定义规则的Laravel数组验证

I've found this question, but I refuse to believe that is not possible to do in a "native" way: Laravel array validation with custom rule

预先感谢

推荐答案

您可以从请求本身获取$prefix:

You could get $prefix from the request itself:

class PhoneLength implements Rule
{
    public function passes($attribute, $value)
    {
        $index = explode('.', $attribute)[1];
        $prefix = request()->input("phones.{$index}.prefix");
    }
}

或在PhoneLength规则构造函数中传递$request,然后使用它.

or pass the $request in the PhoneLength rule constructor, then use it.

这篇关于使用带有附加参数的自定义规则在Laravel中验证数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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