sanity
sanity copied to clipboard
Sanity Studio doesn't validate nested fields when using conditional (custom) required validations
When the ability to conditionally hide a field was launched, we immediately implemented a custom validator that allows making a field required only if a certain condition is true (usually, the condition is that it is visible). This is the validator:
export function makeRequiredIf(conditionFunction, requiredMessage = 'Required') {
return (value, context) => {
if (!value && conditionFunction({ value, ...context })) {
return requiredMessage;
}
return true;
};
}
And this is one application of it:
{
name: 'useTitle',
title: 'Use Title',
type: 'boolean',
},
{
title: 'Title',
name: 'title',
type: 'object',
hidden: ({ parent }) => !parent.useTitle,
validation: Rule => Rule.custom(makeRequiredIf(({ parent }) => parent.useTitle)),
fields: [
{
name: 'en',
title: 'En',
type: 'string',
validation: Rule => Rule.custom(makeRequiredIf(({ parent }) => parent.useTitle)),
},
{
name: 'pt',
title: 'Pt',
type: 'string',
validation: Rule => Rule.custom(makeRequiredIf(({ parent }) => parent.useTitle)),
},
],
},
The expected behaviour is that if useTitle is true and title is completely empty, I get an error in the outside title object, plus two errors in its inner fields en and pt.
Unfortunately I get neither...
The outer error doesn't appear due to an already reported bug at https://github.com/sanity-io/sanity/issues/3238, it only shows if the object is collapsed (very annoying since this blocks publishing without the editor understanding why).
The inner errors also don't show (they don't even run), but in this case it's hard to say whether it is a bug or a feature, because nested validations in empty objects only run in required fields (as they should), but in my case the field is for all intents and purposes required (conditionally, but the condition is true in my hypothesis), it's just that I'm not using Rule.required() but I still wanted the inner validations to run in this case and I don't know how.
If there is a way to conditionally tell Sanity to run inner validations on empty objects, then I apologize and there is no issue, otherwise please consider this a feature request.