Sanity Email Field with Validation

Originally published on 19 February, 2021 by Jacob Stordahl

Here's a great little snippet you can add to a Sanity schema to manage an email address, complete with validation! I came across this snippet over on Eric Howey's blog so make sure you checkout Eric's post to see lots of other great info about field validation in Sanity!

export default {
  name: 'profile',
  type: 'document',
  title: 'Profile',
  fields: [
    ...
    {
      name: 'email',
      type: 'string',
      title: 'Email',
      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])?/,
          {
            name: 'email', // Error message is "Does not match email-pattern"
            invert: false // Boolean to allow any value that does NOT match pattern
          }
        )
    }
    ...
  ]}
© 2021 Jacob Stordahl | built with Steel