Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel do not validate if field is not required

I've got the following request validation:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class OwnerEstate extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'firstname' => 'required_if:type,individual',
            'secondname'=> 'required_if:type,individual',
            'lastname' => 'required_if:type,individual',
            'pin' => 'required_if:type,individual|digits:10',

            'name' => 'required_if:type,legal-entity',
            'eik' => 'required_if:type,legal-entity|digits:9'
        ];
    }
}

And when the type is not individual it still checks for the 'digits:10' validation of the pin and returns an error. How do I disable the other validation if required_if validation does not require the field. (I'm using Laravel 5.5)

like image 582
Angel Miladinov Avatar asked Oct 17 '17 12:10

Angel Miladinov


People also ask

How do I create a custom validation rule in Laravel?

Custom Validation Rule Using Closures $validator = Validator::make($request->post(),[ 'birth_year'=>[ 'required', function($attribute, $value, $fail){ if($value >= 1990 && $value <= date('Y')){ $fail("The :attribute must be between 1990 to ". date('Y').". "); } } ] ]);

What is bail in Laravel validation?

you can easily use bail validation in laravel 6, laravel 7, and laravel 8. If you added more than one validation on your field like required, integer, min and max then if the first is fail then the other should stop to display an error message. right now by default, it prints others too.

What is the method used to configure validation rules in form request?

Laravel Form Request class comes with two default methods auth() and rules() . You can perform any authorization logic in auth() method whether the current user is allowed to request or not. And in rules() method you can write all your validation rule.


1 Answers

digits:10 is completely separate from required_if, so it will validate whether or not the field is required. However, if you want to also allow null or empty values (assuming the field is not required), you can add the rule nullable.

https://laravel.com/docs/5.5/validation#rule-nullable

like image 119
Devon Avatar answered Oct 02 '22 09:10

Devon