Simeon Griggs
Customer Education at Sanity
Simeon is located at Newcastle upon Tyne, UK
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
Not all Unpublished Documents are created equal
Go to GROQ Query for new and unpublished DocumentsGet details of the currently logged in Sanity user
Go to useCurrentUser Custom React Hook