使用带有附加参数的自定义规则验证Laravel中的数组

问题描述 投票:2回答:1

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

我正在使用此自定义规则用于其他工作正常的项目:

<?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)';
}
}

在我的控制器中我做了类似的事情

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

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

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

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

我发现了这个问题,但我拒绝相信不可能以“原生”方式做到:Laravel array validation with custom rule

提前致谢

arrays laravel validation rules
1个回答
2
投票

你可以从请求本身获得$prefix

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

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

© www.soinside.com 2019 - 2024. All rights reserved.