How to make a Dropdown String Field Required

12 replies
Last updated: Nov 24, 2021
How can I make a dropdown string field required?
AI Update

You can make a dropdown string field required by adding a validation rule to your field definition. Here's how:

defineField({
  name: 'category',
  type: 'string',
  options: {
    list: [
      {title: 'Technology', value: 'tech'},
      {title: 'Design', value: 'design'},
      {title: 'Business', value: 'business'}
    ]
  },
  validation: (rule) => rule.required()
})

The key is adding the validation property with rule.required(). This will prevent the document from being published until a value is selected from the dropdown.

You can also customize the error message if you want:

validation: (rule) => rule.required().error('Please select a category')

This works the same way for any string field with a dropdown (created using the options.list property). The validation system happens client-side in the Studio and will show an error indicator on the field if left empty.

Keep in mind that validation only runs in the Studio - if you're creating or updating documents via the API directly, you'll need to implement server-side validation separately.

my field looks like this:

{
  title: "Type of post",
  description: "Pick the format of your post",
  name: "type",
  type: "string",
  options: {
    list: [
      { title: "Article", value: "article" },
      { title: "Video", value: "video" },
      { title: "Podcast", value: "podcast" },
    ],
  },
  validation: (Rule) => Rule.required(),
}
But it's not required 😐
Hmm, I just popped that field into my Studio and it is marking it as required. What version of the Studio are you running?
Or, it is required, but it doesn't mark it as required
I'd love for it to not be an empty choice here, but to choose one of the values
but
initialValue: 'article'
doesn't work
Just upgraded all deps
Initial values will only work on newly created documents.
Re: something not showing up as required, usually that error won't show up until you try to publish the document.
Is it not showing up at all?
oh okay. Actually, this makes sense after a few hours of Zs. πŸ™‚
thanks for clarifying

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.

Was this answer helpful?