
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeGood question! Yes, you can validate the filename by accessing the asset document's originalFilename property. The key issue you've identified is correct - doc.file.asset._ref only gives you the asset reference ID, not the actual filename.
Here's how to validate the filename using custom validation with the Sanity client:
You can use custom validation that fetches the asset document to access the originalFilename:
export default {
name: 'download',
title: 'Download',
type: 'document',
fields: [
{
name: 'name',
title: 'Name',
type: 'string',
validation: (Rule) => Rule.required(),
},
{
name: 'filename',
title: 'Filename',
description: 'This will be the filename which the uploaded file must have.',
type: 'string',
validation: (Rule) => Rule.required(),
},
{
name: 'file',
title: 'File',
type: 'file',
validation: (Rule) => Rule.required().custom(async (value, context) => {
if (!value?.asset?._ref) return true;
const {getClient} = context;
const client = getClient({apiVersion: '2024-01-01'});
// Fetch the asset document to get originalFilename
const asset = await client.fetch(
`*[_id == $assetId][0]{originalFilename}`,
{assetId: value.asset._ref}
);
// Get the expected filename from the parent document
const expectedFilename = context.document?.filename;
if (!expectedFilename) return true;
if (asset?.originalFilename !== expectedFilename) {
return `Uploaded filename "${asset?.originalFilename}" does not match expected filename "${expectedFilename}"`;
}
return true;
}),
},
{
name: 'active',
title: 'Active',
description: 'Is this download active?',
type: 'boolean',
initialValue: true,
},
],
}context.getClient() gives you access to a Sanity client within validation rules_id (which is the _ref value)originalFilename field that stores the actual uploaded filename (this is stored by default as mentioned in the file type documentation)filename field from context.documentapiVersion for your projectoriginalFilename is only stored if the storeOriginalFilename option is true (which is the default according to the file type docs)context.document, so you can reference other fieldsThis approach ensures you're validating against the actual uploaded filename, preventing mismatches when periodically updating files!
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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store