Duddy67
Duddy67

Reputation: 1046

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 ?

Upvotes: 0

Views: 474

Answers (1)

Esmail Shabayek
Esmail Shabayek

Reputation: 405

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

Upvotes: 2

Related Questions