Schema validation rules to enforce image size or file type
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

Simeon Griggs
Customer Education at Sanity