Custom error message shape #3264
-
Consider the following schema: export const FileToUpload = z
.instanceof(File)
.refine((file) => file.size < FILE_SIZE_LIMIT, {
message: `File size should be less than ${FILE_SIZE_LIMIT_MB} MB`,
}); I'm using react-intl package from FormatJS for providing i18n and would like to be able to return a translation object instead of instead of a string, like: export const FileToUpload = z
.instanceof(File)
.refine((file) => file.size < FILE_SIZE_LIMIT, {
message: {
id: 'uploaded_file_size',
defaultMessage: `File size should be less than {max} MB`,
values: { max: FILE_SIZE_LIMIT_MB },
},
}); The first solution that naturally comes to mind is this: const useFileTuUploadSchema = () => {
const intl = useIntl();
return z.instanceof(File).refine((file) => file.size < FILE_SIZE_LIMIT, {
message: intl.formatMessage({
id: 'uploaded_file_size',
defaultMessage: `File size should be less than {max} MB`,
values: { max: FILE_SIZE_LIMIT_MB },
}),
});
}; Unfortunately, it doesn't solve my issue, because I need access to the actual translation object, not a formatted string (I render all translations in a custom component that allows admins to edit translations on the frontend) Interestingly enough, returning a translation object instead of a string seems to work fine, but it's a terrible hack and would require shutting typescript errors, so do you have any suggestion here? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
Is this what you are looking for? const FILE_SIZE_LIMIT = 123456789
const FileToUpload = z.instanceof( File ).superRefine( ( file, ctx ) => {
if ( file.size < FILE_SIZE_LIMIT ) return true
ctx.addIssue( {
code: 'custom',
message: `File size should be less than ${ FILE_SIZE_LIMIT } MB`,
params: {
id: 'uploaded_file_size',
max: FILE_SIZE_LIMIT,
},
} )
} ) If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏 |
Beta Was this translation helpful? Give feedback.
-
Perhaps this could also help: |
Beta Was this translation helpful? Give feedback.
-
Oh yeah, that'll do, thank you! |
Beta Was this translation helpful? Give feedback.
Is this what you are looking for?
If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏
https://github.com/sponsors/JacobWeisenburger