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 ?
CodePudding user response:
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