See Sanity in action 👀 Join us for a live product demo + Q&A →

Setting aspect ratio for image validation in Sanity.io

5 replies
Last updated: Feb 20, 2023
How can i set aspect ratio for image as validation ?
Feb 19, 2023, 8:14 PM
https://www.sanity.io/docs/validation#091e10f957aa instead of geoPoint here just change the variable to
image
what this returns is a
_ref
the value of the ref is the image + dimensions + file type as one string. break the string at the
-
using
split
then find the index where the image dimensions are returned. parse the image dimensions to find the aspect ration
w / h
.
Feb 19, 2023, 9:57 PM
strike that. there is actually undocumented api to get the image dimensions from the ref in the validation:
const {width, height} = getImageDimensions(image.asset._ref)
Feb 19, 2023, 10:17 PM
comes from
import { getExtension, getImageDimensions } from '@sanity/asset-utils'
Feb 19, 2023, 10:17 PM
but according to the source its doing exactly the same thing I said in my first response so you do you.
Feb 19, 2023, 10:23 PM
Rule.required().custom(image =>{
const arr = image.asset._ref.split("-");
let dimension=arr[2];
const res=dimension.split('x');
let width=res[0]
let height=res[1];

const aspectRatio = width / height;
if (aspectRatio===1/1) {
return
} else {
return "The aspect ratio is not 1:1";
}
})
I did like this it worked thank you for the guidance .
Feb 20, 2023, 8:37 AM

Sanity.io – build remarkable experiences at scale

Sanity is a customizable solution that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.