Make a custom validation in laravel 5

3

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

And I needed to do the following: I have a tab on the form that registers the members 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 ... Then if the user wants to register the member, he "checks" the checkbox to fill in the data of the members.

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

I saw a way to create a ServiceProvider for this, but how do I get the field "checkboxes" and check if it has value inside a Request in laravel?

    
asked by anonymous 10.10.2016 / 20:26

2 answers

2

A field that may or may not be required depending on another field ( in your case is checkbox ), you should use required_if that follows the nomenclature:

  

required_if : anotherfield,value

Example:

In the fields below you have input of type checkbox with value true , that if checked input type text with name nome must be at least 1 typed letter:

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

in your FormRequest :

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

Your code would look 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 mount a custom validation, but has a link with the step by step if you prefer .

    
10.10.2016 / 21:31
1

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

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

    }
    else{

    }
}
    
10.10.2016 / 20:35