1
votes

I am trying to add a rule to validate a field. The 'snippet' field needs to be required only if the body field contains HTML. I have the following in my controller store method, but I can't quite figure out how the required_if would work in conjunction with a regex for checking if the field contains HTML:

$newsitem->update(request()->validate([
            'snippet' => 'nullable|max:255|not_regex:/[<>]/',
            'body' => 'required',
            ]));

From the Laravel docs, it looks like the: 'required_if:anotherfield,value' validation rule returns a boolean based on a value, but I need to return a boolean based on a regex check of the body field.

I know I could check if the body is equal to one:

'snippet' => 'required_if:body,==,1|nullable|max:255|not_regex:/[<>]/'

...but I need something that checks if the body contains < or >. (I could add a hidden field in my form submission which would get a value set if the body contained html using javascript, but I wanted to be able to handle this with backend validation.)

Do I need to use a custom validation rule, or can this be handled with the default Laravel validation rules alone?

I have seen in the Laravel docs that you can use the: Rule::requiredIf method to build more complex conditions. Is this something I can use alongside a contains_hmtl function?

'snippet' => Rule::requiredIf($request->snippet()->contains_html),

I really feel like I am missing something here, so any pointers would be much appreciated.

2

2 Answers

1
votes

Try the following regex with RequiredIf:

[
    ...,
    'snippet' => ['nullable', 'max:255', new RequiredIf(function () {
        return preg_match('/<[^<]+>/m', request()->input('body')) !== 0;
    })],
    ...,
]
0
votes

RequiredIf rule accepts a closure which should return a boolean value.

Rule::requiredIf(function () use ($request) {
    //Perform the check on $request->snippet to determine whether it is a valid HTML here
    //Return true if it is valid HTML else return false
}),