I'm trying to write a validation function for this breadcrumb array field and I can verify via console logs that it gets to the
return "<error message>"
step, but even though it's returning a string it still passes validation and updates correctly when saved.
This is the validation function...
validate: (value, siblingData) => {
console.log(`value: ${value}`, value);
console.log(`siblingData: ${siblingData}`, siblingData);
if (siblingData?.data?.variant === 'blogPost') {
console.log(`variant is blogPost`);
if (value?.length > 1) {
console.warn(`more than one breadcrumb`);
return "Blog posts shouldn't have more than one breadcrumb";
} // there's another clause here but it's irrelevant
}
return true;
},
Attached is the console output.
To be clear, in the Admin UI I'm seeing this update successfully even though it should be failing validation.
a string return is a truthy value. maybe you actually have to throw an error?
throw new Error("Blog posts shouldn't have more than one breadcrumb")
In theory it's truthy but the way Payload validation should work when returning a string is that it should show that error next to the relevant field, as explained here:
https://payloadcms.com/docs/fields/overview#validation
I have other examples that are currently working that utilize this and it's showing the correct behavior, but not for this one which is confusing me.
ah ok, my bad. that was just an initial thought I had purely looking at your code example.
No problem!
I was also able to verify that other forms of validation do work on that field (Making the properties required) which I didn't have before but should have. Either way the custom validation function above is not working either way
I'm running Payload v1.16.11 btw, but plan to update to 1.16.17 later today so I will see if it's still a problem after that
Is it just this field type? Could you troubleshoot by adding custom validation to a simple text field?
@Jarrod It does seem to just be for this field type. Validation seems to correctly fail for a simple test text field in the same collection like this...
{
type: 'text',
name: 'testValidation',
validate: (value) => {
if (value === 'test') {
return 'You cannot use the word "test" in this field';
}
return true;
},
},
I have opened a GitHub issue detailing this here:
https://github.com/payloadcms/payload/issues/2281Perfect, thank you 🙏
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.