Validating custom entry field through custom validator rules not working #16597
-
I'm trying to add custom validator rules for certain custom fields on a specific entry section, ultimately I need to use on and where to have control of when the validation is enabled, rather than setting as required on the field itself. The fields being targeted are entry fields. I'm using the EVENT_DEFINE_RULES event, which I believe is correct. In this example, the code is 100% firing, but not returning a validation error, the customField handle is an example but using a real handle, it doesn't cause a validation error to be raised as excepted. Event::on(
Entry::class,
Entry::EVENT_DEFINE_RULES,
static function (DefineRulesEvent $event) {
/** @var Entry $entry */
$entry = $event->sender;
$sectionHandle = $entry->getSection()?->handle;
if ($sectionHandle === 'exampleSection') {
$event->rules[] = ['field:customField', 'required'];
}
}
); As the rule targets an entry field, I wondered if the data does not work with the required validator because the actual data returned is an EntryQuery and not the result of the query, which is the value wanting to be validated. Therefore I did this: $event->rules[] = ['field:customField', 'required', 'isEmpty' => function ($query) {
return empty($query->one());
}]; Which then checks for an empty value from the result of the EntryQuery and seems to work and adding on and when allows this rule to be custom based on the result of another condition. However is there a better way to do this? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
I just tested your first example and it’s working on my end. A little too well: it’s preventing new entries from being created in that section because the custom field value is obviously not filled in yet at that point. Adding What type of field are you working with? Does the section have multiple entry types? |
Beta Was this translation helpful? Give feedback.
RequiredValidator
will check if the value isnull
,[]
, or''
by default. So yeah you’d need to override itsisEmpty
property with a custom callback that returns!$value->exists()
.There’s no way to automate it since the required validator has no idea that it’s validating a custom field;
field:customField
is just some arbitrary attribute name that it’s going to use to get the value from the model being validated ($value = $model->$attribute
).