how to validate atleast one value of form input array in laravel request?

Viewed 255

I am passing array input to store function .

  <div class="col-md-4 form-group-sub mt-2 date_">
   <input type="text" name="date[]" class="form-control datepicker" placeholder="Date">
  </div>
                                               

this array should be have atleast one field filled . If all the values are null i don't to submit this form how shoult i validate in request

public function rules()
    {
        return [
           
            'date.*' => '?'

        ];
    }

2 Answers

this array should be have atleast one field filled . If all the values are null i don't to submit this form

This will pass
['some date', NULL, NULL, NULL]


This will fail
[NULL, NULL]

This will fail
[]

Anything other than array will fail.

Use a combination of array, min:1 and a custom rule that checks the null condition.

https://laravel.com/docs/7.x/validation#rule-array

https://laravel.com/docs/7.x/validation#rule-min

https://laravel.com/docs/7.x/validation#custom-validation-rules

public function rules()
    {
        return [
            'date' => ['array', 'min:1', new DateCheck]
        ];
    }

DateCheck rule will check, that there should be at least one element in the array, that is not null.

Inside DateCheck Rule

    public function passes($attribute, $value)
    {
        $dates = $value;
        foreach($dates as $date){
           if(isset($date)){
               return TRUE;
           }                      
        }
        return FALSE;
    }

     public function message()
    {
        return 'There should be at least one date that is not NULL.';
    }


Related