In a current document
group I'm trying to find a way to only allow validation when the boolean is set to true
:
{
title: 'Has the movie been released?',
name: 'released',
type: 'boolean',
initialValue: true
}
fooBar.ts:
export default {
title: 'Foo',
name: 'foo',
group: 'general',
type: 'object',
fields: [
{
title: 'Alpha',
name: 'alphaBool',
type: 'boolean',
description: 'Random text',
initialValue: false
},
{
title: 'Alpha Location',
name: 'alphaLoc',
type: 'string',
hidden: ({ parent }) => parent?.alphaBool !== true,
validation: Rule => Rule.required()
}
]
};
but this current implemented approach throws a required error even though it might be set to false
. I've tried to see if I could pass down either parent
or document
from validation
so I could attempt to get the value of alphaBool
but they both show undefined
:
validation: (rule, parent, document) => console.log(rule, parent, document)
but I'm allowed to see parent
and document
objects in hidden
.
Research
- Conditional fields
- Field Groups
- Conditional validation of string
- Boolean
- Now you see them, now you don’t. Introducing Conditional Fields.
- Validation
- Optional validation for hidden fields
In Sanity 2.35.0 how can I run validation only if the boolean value is set to true
?
CodePudding user response:
If I correctly understand your question, you can use custom validations for this.
Example:
{
title: 'Alpha',
name: 'alphaBool',
type: 'boolean',
description: 'Random text',
initialValue: false
},
{
title: 'Alpha Location',
name: 'alphaLoc',
type: 'string',
hidden: ({ parent }) => parent?.alphaBool !== true,
validation: (Rule) => Rule.custom((value, { document: { alphaBool } }) => {
return alphaBool && !value ? "Field required" : true
})
}
With Rule.custom
, you can access the value of the field and the context
object of the document. In this example, if alphaBool
is set to true
and the current field's value is an empty string, then it will throw a Field required
validation message. If alphaBool
is false
, it will not validate anything.