如何在Laravel 5.0中验证数组输入 [英] How do I validate Array inputs in Laravel 5.0

查看:86
本文介绍了如何在Laravel 5.0中验证数组输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张桌子,用户可以在其中填写信息.但是,用户可以添加行和/或删除行.我为此使用了克隆功能.

I have a table, where the user can fill in information. However, the user can add rows and/or delete rows. I used a cloning function for that.

我的html如下:

<input type="text" class="form-control" name="TB1_a[]">
<input type="text" class="form-control" name="TB1_b[]">

如您所见,它是一个数组输入.因此,如果用户添加一行,我将在TB1_a []和TB1_b中存储两个值. 现在,我要制定规则,以便如果用户在TB1_a [0]中输入信息,我想使TB1_b [0]为必需,但是如果同时 TB1_a [0]和TB1_b都有效[0]为空.

As you can see, it is an array input. So if the user adds a row, I'll have two values stored in TB1_a[] and TB1_b. Now, I would like to make my rules so that if the user enters information inside TB1_a[0], I would like to make TB1_b[0] required, but valid if both TB1_a[0] and TB1_b[0] are empty.

我的验证规则:

'TB1_a.*' => 'required_with:TB1_b.*',
'TB1_b.*' => 'required_with:TB1_a.*'

但是,这些规则无法检测到我正在引用数组,这意味着Laravel无法检测到.*".我还要指出的是,此逻辑与Laravel 5.4完美配合,但是我不得不降级Laravel,现在它停止工作了.有什么帮助吗?

However, these rules are unable to detect that I am referring to an array, meaning Laravel does not detect the '.*'. I would also like to point out that this logic was working perfectly with Laravel 5.4, but I have had to downgrade my Laravel and now it stops working. Any help please?

推荐答案

据我所知,此[.*]符号是在Laravel 5.2+中引入的.因此,要实现阵列验证,您需要添加自定义规则. 参考链接

As I know, this[.*] notation was introduced in Laravel 5.2+. So, to achieve the array validation, you would need to add custom rules. Reference Link

public function rules()
{
  $rules = [
    'name' => 'required|max:255',//add more static rules as you need
  ];

  foreach($this->request->get('TB1_a') as $key => $val)
  {
    $rules['TB1_a.'.$key] = 'required_with:TB1_b.'.$key;
  }

  foreach($this->request->get('TB1_b') as $key => $val)
  {
    $rules['TB1_b.'.$key] = 'required_with:TB1_a.'.$key;
  }

  /*
  To combine the both validation rules in 1 loop. considering number of both fields are always equal
      foreach($this->request->get('TB1_a') as $key => $val)
      {
        $rules['TB1_a.'.$key] = 'required_with:TB1_b.'.$key;
        $rules['TB1_b.'.$key] = 'required_with:TB1_a.'.$key;
      }  
  */
  return $rules;
}

这篇关于如何在Laravel 5.0中验证数组输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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