Muhammad
Muhammad

Reputation: 634

How do I validate Array inputs in 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.

My html looks like:

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

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.

My validation rules:

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

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?

Upvotes: 1

Views: 647

Answers (1)

jaysingkar
jaysingkar

Reputation: 4435

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;
}

Upvotes: 2

Related Questions