Filename validation for file type field in Sanity schema
Good 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:
Solution: Custom Validation with Asset Lookup
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,
},
],
}How it works:
- The
context.getClient()gives you access to a Sanity client within validation rules - You query the asset document using its
_id(which is the_refvalue) - The asset document has an
originalFilenamefield that stores the actual uploaded filename (this is stored by default as mentioned in the file type documentation) - You compare it against your expected
filenamefield fromcontext.document
Important notes:
- This validation is asynchronous and runs when you try to publish/save the document
- Make sure to use an appropriate
apiVersionfor your project - The
originalFilenameis only stored if thestoreOriginalFilenameoption istrue(which is the default according to the file type docs) - The validation has access to the entire document via
context.document, so you can reference other fields
This approach ensures you're validating against the actual uploaded filename, preventing mismatches when periodically updating files!
Show original thread4 replies
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.