Condition in request Condition

Asked

Viewed 946 times

2

I have a request class called PessoaRequest. In this class, I validate my form to register people.

But now, some information has appeared to be entered that are not mandatory: father’s and mother’s name. When I have this information, I mark a checkbox creating the html fields to insert this data.

In class PessoaRequest, I have the following rules:

return [
      'name'       => 'required|min:3|alpha', //obrigatório com pelo menos 3 caracteres alfabéticos
      'telefone_1' => 'required',//obrigatório e deve ser um email
      'email'      => 'required'
      [....]
    ];

In it ,I can not put rule for fields that ask for father’s and mother’s name , because not mandatory.

I wonder if there’s a way to put probation rule inside Request, guy :

// Se o checkbox for marcado
if($chkPais == 1 ) {
      'nome_pai' => 'required',
      'nome_mae' => 'required'
}

If not, how could this validation ?

From now on, thank you.

1 answer

4


Yes, I usually do that a lot in the Laravel 5.

public function rules() 
{
    $rules = ['nome' => 'required', 'email' => 'required|email'];

    // Se o valor da checkbox for marcado

    if ($this->has('check_box'))
    {
         $rules['pai'] = 'required';
         $rules['mae'] = 'required';
    }


    return $rules;
}

You only add the validations of pai and mae if your checkbox value is checked.

Just remembering that when we create a Request, we’re extending the Request standard used in Laravel. Then, through the pseudo variable $this, we can access methods like get, has and only.

The method has in this case serves to verify if any field check_box was sent by a form. If empty, has will return false. But if you return anything, you will fall if, which it will add to the $rules the valors pai and mae for validation.

  • Good afternoon, thanks for the quick return. I will test here and I already speak .

  • Good afternoon @Wallace , man, gave it right here. When give the 7min , mark as solved. Vlw

  • All right, @Henriquefelix. I’m glad it helped. I didn’t think I could help you so fast :D

  • So , I’m a little late to deliver this registration page with this new rule. So , fell like a glove.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.