Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel validation required_if doesn't work

I want to make a field mandatory if another field contains the "{" character.
I’ve tried several combinations but it looks like Laravel doesn’t apply the rule at all.

public function rules()
{   
    $rules = [ 
        'title' => 'required', 
        'url' => 'required',
        'model_name' => 'required_if:url,url:regex:/{/',
        // The following doesn't work either:
        // 'model_name' => 'required_if:url,url:not_regex:/{/',
        // 'model_name' => 'required_if:url,regex:/{/',
        // 'model_name' => 'required_if:url,not_regex:/{/',
    ];  

    return $rules;
} 

Any idea ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you would like to construct a more complex condition for the required_if rule, you may use the Rule::requiredIf method. This method accepts a boolean or a closure. When passed a closure, the closure should return true or false to indicate if the field under validation is required:

use Illuminate\Validation\Rule;
use Illuminate\Support\Str;

public function rules()
{   
    $rules = [ 
        'title' => 'required', 
        'url' => 'required',
        'model_name' => Rule::requiredIf(Str::contains($this->url, '{')),
    ];  

    return $rules;
} 

I hope this workaround help you

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading