Validation icon indicating copy to clipboard operation
Validation copied to clipboard

Given a multirule validator, is there a usage pattern for testing a single rule?

Open paxperscientiam opened this issue 3 years ago • 0 comments

Thanks for the awesome library!

So, here's what I'm trying to accomplish with use-case.

Goal: Given a multirule validator, with a mix of optional and required inputs, determine how to test a single arbitrary input.

Use case: presenting inline error text at

level immediately after an input field has changed. In such a scenario, the goal is not to validate the entire form, but just a single input field.

The below code is my attempt at this

// Injectable class for form validation

namespace App\Validations;

use Respect\Validation\Validator as V;

class UserSettingsFormValidator
{
    public readonly V $rules;

    public function __construct()
    {
        $this->pointsRule = (new V())->intVal();
        $this->planPointsRule = (new V())->number();
        $this->rules = (new V())
            ->key("plan-selection", $this->pointsRule)
            ->key("plan-points-goal", $this->planPointsRule, false);
    }

    public function getInlineError($data)
    {
        try {
            $this->rules->check($data);
        } catch (Respect\Validation\Exceptions\NestedValidationException $e) {
            return $e->getMessage();
        } catch (Respect\Validation\Exceptions\ValidationException $e) {
            return $e->getMessage();
        } catch (Respect\Validation\Exceptions\Exception $e) {
            return $e->getMessage();
        } catch (\Exception $e) {
            return $e->getMessage();
        }

    }
}
// pseudo code
// Handling POST request for single input fields of a given form
 if ("input-name-one" == $posted_input) {
   // graph associated rule from UserSettingsFormValidator and validate
 } else if ("input-name-two" == $posted_input) {
  // graph associated rule from UserSettingsFormValidator and validate
 } // etc
// etc

As you can see, this approach for validating a single input is cumbersome. I wonder, is it possible to setup a validator -- with a mix of required and optional fields -- that will validate a single input without worrying about omitted required inputs?

I hope that makes sense. Happy to clarify if it doesn't :)

paxperscientiam avatar Apr 01 '22 18:04 paxperscientiam