Simeon Griggs
Customer Education at Sanity
Uses @sanity/asset-utils to validate an uploaded image by its ID
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.
Customer Education at Sanity
Automatically format code blocks using Prettier to enforce consistency across all documents.
Go to Format code blocks with PrettierGet instant Telegram notifications when new comments are posted, with direct links to your Sanity Studio.
Go to Telegram alerts for new commentsPrevent references to large files to reduce the chances of high bandwidth usage
Go to Schema validation rules to enforce maximum file sizeNot all Unpublished Documents are created equal
Go to GROQ Query for new and unpublished Documents