Do a custom validation on Laravel 5

Asked

Viewed 2,387 times

3

I have a system on Laravel 5. I have a Form Request validating the fields of a form with some rules.

And here’s what I needed to do: I have a tab on the form that registers the partners of a company. The user has the option to register or not the members. I have a checkbox that controls this, it comes "false" by default... So if the user wants to register the partner, he "checks" the checkbox to fill in the membership data.

I would like to do a function that if the partner’s checkbox is checked, it does the validation in the fields: - name, - participation. Otherwise, it does not validate in these fields.

I saw a way to create a Serviceprovider for this, but how will I take the field "cadsocios" (checkbox) and check if it has value within a Request in the Standard?

  • what is the version of your Laravel?

2 answers

2


A field that may or may not be mandatory that depends on another field (in your case is a checkbox), should use the required_if which follows the nomenclature:

required_if:anotherfield,value

Example:

In the fields below there’s a input of the kind checkbox with the value true, that if the input of the kind text by the name of nome have to have at least 1 typed letter:

<p>
    <input type="checkbox" value="true" name="liberar">
    <input type="text" value="" name="nome">
</p>

in his FormRequest:

public function rules()
{
    return [
         'nome' => 'required_if:liberar,true'
    ];
}

Your code would look something like this:

<p>
    <input type="checkbox" value="true" name="socio">
    <input type="text" value="" name="nome">
    <input type="text" value="" name="participacao">
</p>

public function rules()
{
    return [
         'nome' => 'required_if:liberar,true',
         'participacao' => 'required_if:liberar,true'
    ];
}

I see no reason to build a custom validation, but, has a step-by-step link, if you prefer.

  • It was a ball show... but there was an unforeseen event in another field...

  • in the name field, it is an input text that can have several name fields = name[] (array), so it does not accept in the validation, since even being empty, it considers existing...?

  • If you can open another question has been solved this problem is now another. Got it

  • Has yes to validate array

  • On the question link you have the array and in_array validations on the Laravel website or open another question, fine?

  • opened another question: http://answall.com/questions/158381/valida%C3%A7%C3%a3o-no-Laravel-5

Show 1 more comment

1

In the Service Provider that does the validation you can use the $this, why it references the Controller Request.

public function rules()
{
    if($this->nome_do_campo){

    }
    else{

    }
}

Browser other questions tagged

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