Validation error prevents publishing when both internal and external link fields are filled
I can see the issue in your validation code! The problem is with what you're returning from your rule.custom() function.
Your current validation logic is returning the opposite of what it should:
validation: (Rule: any) =>
Rule.custom((context: any) =>
context.article && context.url ? true : "Du kan ikke lenke til både artikkel og ekstern URL"
),This returns true when both fields are filled (which is what you want to prevent), and shows an error when they're not both filled. You need to flip the logic.
Here's the corrected version:
{
title: "Artikkel",
name: "article",
type: "reference",
to: [{ type: articleDocument.name }],
description: "Lenke til en artikkel på Löplabbet",
validation: (Rule) =>
Rule.custom((value, context) => {
// Show error if BOTH article and url are filled
if (context.parent?.article && context.parent?.url) {
return "Du kan ikke lenke til både artikkel og ekstern URL";
}
return true; // Valid in all other cases
}),
},
{
title: "URL",
name: "url",
type: "string",
description: "Lenke til en ekstern side",
validation: (Rule) =>
Rule.custom((value, context) => {
// Show error if BOTH url and article are filled
if (context.parent?.url && context.parent?.article) {
return "Du kan ikke lenke til både ekstern URL og artikkel";
}
return true; // Valid in all other cases
}),
},Key changes:
- Use
context.parentto access sibling fields (as explained in the Sanity validation docs) - Return the error message string when the validation fails (both fields filled)
- Return
truewhen validation passes (any other case)
The validation function should return:
trueif the value is valid- A string error message if the value is invalid
You had these reversed in your original code, which is why it was blocking publishing even when validation should pass.
Show original thread3 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.