Schema validation rules to enforce image size or file type

By Simeon Griggs

Uses @sanity/asset-utils to validate an uploaded image by its ID

schema.ts

import { getExtension, getImageDimensions } from '@sanity/asset-utils'

// ...then in your schema
defineField({
  name: `image`,
  type: `image`,
  validation: (rule) =>
    rule.custom((value) => {
      if (!value) {
        return true
      }
      
      const filetype = getExtension(value.asset._ref)

      if (filetype !== 'jpg' && filetype !== 'png') {
        return 'Image must be a JPG or PNG'
      }
      
      const {width, height} = getImageDimensions(value.asset._ref)

      if (width < 1200 || height < 630) {
        return 'Image must be at least 1200x630 pixels'
      }

      return true
    }),
})

When assets are uploaded to Sanity's CDN they are given deterministic IDs which contain information about the original file's dimensions and file format.

The @sanity/asset-utils library contains a set of helpful functions to easily extract those details from an asset's ID.

In this snippet, we use those values to inform a custom validation rule for an Image field.

Contributor

Other recipes by the contributor

Format code blocks with Prettier

Official(made by Sanity team)

Automatically format code blocks using Prettier to enforce consistency across all documents.

Simeon Griggs
Go to Format code blocks with Prettier

Telegram alerts for new comments

Official(made by Sanity team)

Get instant Telegram notifications when new comments are posted, with direct links to your Sanity Studio.

Simeon Griggs
Go to Telegram alerts for new comments