Skip to content
  • SANITY.io

Validation snippets for SANITY.io

July 18, 2020 1 Min

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.

Required field

The simplest type of validation - make a field required without any other custom rules.

{
name: "title",
title: "Title",
type: "string",
validation: (Rule) => Rule.required(),
},

RegEx Validation

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.

{
name: "email",
title: "Email",
type: "string",
validation: (Rule) =>
Rule.regex(
/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g,
{
name: "email", // Error message is "Does not match email-pattern"
invert: false, // Boolean to allow any value that does NOT match pattern
}
),
},

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.

{
name: "postal",
title: "Postal Code",
type: "string",
validation: (Rule) =>
Rule.custom((postal) => {
if (typeof postal === "undefined") {
return true // Allow undefined values, remove if the field is required
}
const regex = /([ABCEGHJ-NPRSTVXY]\d[A-Z])[\s\-]?(\d[A-Z]\d)/gi // Regex pattern goes here
if (regex.test(postal)) {
return true
} else {
return "Not a valid postal code" // Error message goes here
}
}),
},

URL validation

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.

{
name: "link",
title: "Link",
type: "url",
validation: (Rule) =>
Rule.required().uri({
allowRelative: true, // Allow relative links
relativeOnly: false, // Force only relative links
scheme: ["https", "http", "mailto"], // Default is ["https", "http"]
}),
},

Illustrations by Diana Valeanu
Design inspired by Gatsby-Absurd
© 2020 Eric Howey