How to validate image dimensions in Sanity uploads

3 replies
Last updated: Aug 9, 2021
not sure if this is what you’re looking for, but this thread might help? https://stackoverflow.com/questions/58567054/how-can-i-validate-the-dimensions-of-an-uploaded-image-in-sanity
AI Update

Great find! That StackOverflow thread is exactly what you need for extracting image dimensions from Sanity asset IDs.

Sanity encodes image metadata directly into the asset ID using this format: image-{hash}-{width}x{height}-{format}. For example: image-abc123def456-1920x1080-jpg.

Here are the main approaches for extracting dimensions:

Manual parsing with regex:

const pattern = /^image-([a-f\d]+)-(\d+x\d+)-(\w+)$/
const decodeAssetId = id => {
  const [, assetId, dimensions, format] = pattern.exec(id)
  const [width, height] = dimensions.split("x").map(v => parseInt(v, 10))
  return { assetId, dimensions: { width, height }, format }
}

Using in custom validation: This is particularly useful for enforcing dimension requirements:

{
  title: "My Image",
  name: "image",
  type: "image",
  validation: Rule => Rule.custom(image => {
    if (!image) return true
    const { dimensions } = decodeAssetId(image.asset._ref)
    if (dimensions.width < 500) return "Image must be at least 500px wide"
    if (dimensions.height > 2000) return "Image must be less than 2000px tall"
    return true
  })
}

Alternative approach - querying metadata: When you have access to the full asset object in your queries, you can also get dimensions from the metadata structure:

*[_type == "myDocument"] {
  image {
    asset-> {
      metadata {
        dimensions {
          width,
          height
        }
      }
    }
  }
}

The regex approach from the StackOverflow thread is perfect for validation rules and client-side code where you only have the asset reference ID. It's a stable, documented pattern that Sanity uses consistently for image asset IDs.

Show original thread
3 replies
there’s a really nice regex + function combo there you can use to snip the dimensions from
asset._ref


const pattern = /^image-([a-f\d]+)-(\d+x\d+)-(\w+)$/

const decodeAssetId = id => {
  const [, assetId, dimensions, format] = pattern.exec(id)
  const [width, height] = dimensions.split("x").map(v => parseInt(v, 10))

  return {
    assetId,
    dimensions: { width, height },
    format,
  }
}
there’s a really nice regex there you can use to snip the dimensions from
asset._ref

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?