0
votes

Some form fields in my laravel 5.5 application have validation rules that run against a remote API and take quite some time. I would thus only want to run these expensive checks when the field value changes (is different from the value currently stored in the model).

Is there something that implements this already, e.g. as a rule similar to sometimes?

I would image it like this: only_changed|expensive_validation|expensive_validation2. The latter rules would only be executed when the field value has changed.

1
You will be needing javascript for validation on handling input changes.Poldo
No, this should be possible purely in PHP.cweiske
For the field to be validated you need to call a post method. So it means the form need to be submitted before it will validate.Poldo

1 Answers

0
votes

Assuming you are using a custom Request class, the rules() method expects an associative array to be returned before it applies the validation.

You can build your array of rules dynamically using the request contents before applying the validation like so:

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    $validation_array = [
        'name'     => 'required|string|max:255',
    ];

    if ($this->my_field === $some_condition) {
        $validation_array = array_merge($validation_array. [
            'my_field' => "required|expensive_validation|expensive_validation2"
        ]);
    }

    return $validation_array;
}

Note: I haven't run this yet but the principle should be fine.