Content has not been updated for more than 2 years, proceed with caution.
Validation snippets for SANITY.io
A great feature of SANITY.io is the ability to add field validation to schema types. This can ensure data conforms to specific patterns, e.g. a ZIP code is actually a valid ZIP code or an email field is a valid email. This brief article covers just a few of the ways you can validate a field, I will add more snippets over time as I find useful ones.
The simplest type of validation - make a field required without any other custom rules.
Some field types, like string, allow you to test against a specified regex pattern to ensure the data matches a certain pattern. This is really handy for things like postal codes, email addresses and more.
Custom RegEx Validation
Sanity also provides a custom validation type which can be used on any field and allows for more complex validation patterns and even testing against other fields. In this example the field can be empty BUT if the field is completed then it must meet the regex pattern. To make the field both required and match a regex pattern you can remove the first if statement that checks whether the field is undefined.
This validation ensures that a field is filled in with a valid url. In this example it allows relative links and also allows mailto links. Relative links can be required with the relativeOnly option.