0

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 ?

2
  • required_if:url,regex:/{/ this should work Commented Dec 18, 2022 at 9:17
  • @AbdullaNilam No, it doesn't. Commented Dec 18, 2022 at 9:20

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.