๐Ÿ”ฎ Sanity Create is here. Writing is reinvented. Try now, no developer setup

Issue with schema validation in Sanity Studio resolved by adding the required() function.

8 replies
Last updated: Aug 14, 2023
Hello ๐Ÿ‘‹ Schema validation question. I'm trying to add a rule to require an array of reference to have length 1 using the
length
function here . It doesn't seem to work on the Studio side. Attached the field declaration in the shema. Does anyone know what I'm doing wrong?
Aug 11, 2023, 11:07 AM
There's also a ts error
Aug 11, 2023, 11:07 AM
Try adding
required()
as follows:
validation: (Rule) => Rule.required().length(1).error('Must have at least 1 element.'),
Aug 11, 2023, 11:35 AM
Nice, this works. Thank you!
Aug 11, 2023, 11:41 AM
The TS error is also gone
Aug 11, 2023, 11:41 AM
I didn't realise it was required to chain the
.error
function
Aug 11, 2023, 11:41 AM
Glad to hear the issue is sorted :) The
.error()
is optional but I think in your case, it was the
required()
bit that was missing.
Aug 11, 2023, 11:43 AM
I did try this without
.required()
and seems to work the same as having it. The validation error is there
Aug 11, 2023, 11:44 AM
Looks like you can also use
max()
function. So something like this:
validation: (Rule) => Rule.max(1).error('Must have at least 1 element.'),

Aug 14, 2023, 9:49 AM

Sanityโ€“ build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?