Skip to content
Advertisement

Why is my field validated even if it’s not required?

I have a request that takes several input. I want the ‘salary’ input to be validated only if the salary_type is equal to “exact”. Else, I don’t want to have any message about it.

However, now, even if salary_type is equal to “range”, I still get an error that “salary must be an integer”.

How can I make sure there isn’t any error unless the field is required?

Thanks!

<?php

namespace AppHttpRequests;

use IlluminateFoundationHttpFormRequest;

class StoreJobOfferRequest 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 [
            'title' => 'required|string|min:3',
            'description' => 'required|string|min:10',
            'city' => 'required|string|min:3',
            'salary_type' => 'required|in:range,exact',
            'min_salary' => 'required_if:salary_type,range|integer|min:0',
            'max_salary' => 'required_if:salary_type,range|integer|min:0',
            'salary' => 'required_if:salary_type,exact|integer|min:0',
            'fieldsOfWork' => 'required|exists:field_of_works,id',
            'job_type.*' => 'required|exists:job_types,id',
            "trainings.*" => 'required|exists:trainings,id',
            "availability.*" => 'required|exists:trainings,id'
        ];
    }
}

Advertisement

Answer

required and required_if do not stop the rest of the validation rules from being executed. It just expects the value not to be null, an empty string, and empty Countable object or an uploaded file with no path. If the field is set, the required rule will just be skipped and the next rule is applied.

So, the required_if rule for salary will skip if salary_type is not 'exact', and continue validating if it’s an integer and min 0. This behavior is confusing to a lot of new Laravel developers.

There is an exclude_if rule that does what you probably expect:

'salary' => 'exclude_if:salary_type,exact|integer|min:0',

This will exclude the whole field under validation from the request data that will be returned by validate() and $request->validated() methods if the condition is not met. So if salary_type is not 'exact', the salary field will be gone but the validation will pass.

If salary_type is 'exact', however, it will be validated for being a min 0 integer value.

Please note that the exclude_if rule was added in Laravel 6, so this doesn’t work for previous versions of Laravel. See https://laravel.com/docs/8.x/validation#conditionally-adding-rules for details on conditional validation.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement