DEV Community

Cover image for Access Current Entry in Custom Validation Rule
Julia Lange for visuellverstehen

Posted on

1 3

Access Current Entry in Custom Validation Rule

Sometimes, when writing a custom validation rule for a Statamic project, I find myself in a position where I need information about the current entry I am editing.

But because validation rules don’t provide this kind of information, I've tried some hacky stuff like reading the current entry id from the request URL. However that doesn't work if you have more than two stacks open at once.

Luckily I discovered that Statamic did a nifty thing with their own validation rules. Just like unique_entry_value, unique_term_value & unique_user_value you can pass the current id, collection and the site like this to your validation rule:

resources/blueprints/collections/pages/default.yaml

validate:
   - 'custom_validation_rule:{id},{collection},{site}'
Enter fullscreen mode Exit fullscreen mode

Those values can then be found in the parameters array inside the validate method.

App/Validation/CustomValidationRule.php

class CustomValidationRule
{

   public function validate($handle, $value, $parameters, $validator)
   {
      $id = $parameters[0];
      $collection = $parameters[1];
      $site = $parameters[2];

      // Do stuff with it.
   }
}
Enter fullscreen mode Exit fullscreen mode

That's all there is to it. Simple, but powerful. Happy coding, everyone!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay