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}'
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.
}
}
That's all there is to it. Simple, but powerful. Happy coding, everyone!
Top comments (0)