Skip to content

Validation exception labels#6

Draft
gwillz wants to merge 2 commits intomasterfrom
feat/validation-labels
Draft

Validation exception labels#6
gwillz wants to merge 2 commits intomasterfrom
feat/validation-labels

Conversation

@gwillz
Copy link
Copy Markdown
Collaborator

@gwillz gwillz commented Oct 30, 2023

So adding labels here isn't difficult, but the workflow might just be a bit clunky.

For models example I imagine:

$labels = [ 'name' => 'Human name' ];

try {
  $model->validate();
} catch (ValidationException $exception) {
  $exception->setLabels($labels);
  throw $exception;
}

It's all a bit blah.

Validator

For integrating with the standard validation class (a la Sprout) it would look like this. Much tidier.

$valid = new RulesValidator($_POST);
$valid->required(['name', 'email']);

$labels = [
  'name' => 'Full name',
  'email' => 'Email Address',
];

$errors = $valid->getErrors();

if (!empty($errors)) {
  throw (new ValidationException)
     ->addErrors($errors)
     ->setLabels($labels);
}

The rules validator could actually house this code and expose a validate() helper method I reckon.

More ideas

A half-baked idea: we could extend our concept of scenarios to accept alternate validator instances. Because really a 'scenario' is just an alternate set of validation checks.

$valid = new RulesValidator($_POST);
$valid->check('email', 'Validity::email');
$valid->setLabels(['email' => 'Email Address']);

// Pass in this validator instance, the exception carries fields + labels all the way through
$model->validate($valid);

// OR
$model = MyModel::findOne(['id' => $id]);
$model->update($_POST);

// Pulls rules from a specific scenario in the MyModel::rules()
$valid = new RulesValidator($model, 'scenario-name');

// Alternate, more agricultural.
$valid->fromScenario($model, 'scenario-name');

// Add labels, additional rules, etc.
$valid->setLabels(['email' => 'Email Address']);

// Same deal, happy labels + etc.
$model->validate($valid);

@gwillz gwillz requested a review from jamiemonksuk October 30, 2023 03:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant