Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Form validation with logic operators

When a user fill Message (textarea) he/she can't fill Date,Time,Venue values.
Those three fields will consider only when Message is empty and all those three fields are filled.
How to do this using Laravel form validation? Is it possible to define these logic in Request's rule method?
I am new for Laravel.
Thanks in advance

This is my form

like image 253
Shani Avatar asked Jun 21 '16 04:06

Shani


1 Answers

You can achieve this (serverside) by using conditional validation rules:

  • required_if:anotherfield,value,...
  • required_unless:anotherfield,value,...
  • required_with:foo,bar,...
  • required_with_all:foo,bar,...
  • required_without:foo,bar,...
  • required_without_all:foo,bar,...

I would say for your case:

  • date is required unless message is filled-in
  • time is required unless message is filled-in
  • venue is required unless message is filled-in
  • message is required without all date, time, venue

Chain rules if you need by separating them with pipe

Follows an example snippet. Use this method inside your ExampleFormRequest extending Request

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    $rules = [];

    switch ($this->method()) {
        case 'PATCH':
        case 'PUT':
        case 'POST':
            $rules = [
                'date'    => 'required_without:message',
                'time'    => 'required_without:message',
                'venue'   => 'required_without:message',
                'message' => 'required_without_all:date,time,venue',
                ];
            break;
        default:
            // Perform no alteration to rules
            break;
    }

    return $rules;
}

Checkout documentation here

like image 168
alariva Avatar answered Sep 30 '22 06:09

alariva