Skip to content

Commit

Permalink
Refactor image validation in imageValidationZodSchema.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
edwardspresume committed Mar 7, 2024
1 parent 555088c commit 18b9c47
Showing 1 changed file with 10 additions and 11 deletions.
21 changes: 10 additions & 11 deletions src/lib/validations/imageValidationZodSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,27 @@ export const SUPPORTED_IMAGE_TYPES = ['jpeg', 'png', 'webp', 'avif', 'gif'];

export const IMAGE_VALIDATION_ERROR_MESSAGES = {
noFileUploaded: 'Please upload a file.',
notAnImage: 'The file you uploaded is not an image.',
fileEmpty: 'The file you uploaded is empty.',
fileTooLarge: `The file size must be less than ${MAX_FILE_SIZE_MB} MB.`,
unsupportedImageType: `The image type you uploaded is not supported. Please upload an image of one of the following types: ${SUPPORTED_IMAGE_TYPES.join(
', '
)}.`,
fileTooLarge: `The file size must be less than ${MAX_FILE_SIZE_MB} MB.`
)}.`
};

export const imageValidationZodSchema = z.object({
uploadedImage: z
.instanceof(File)
.refine((file) => file.size > 0, IMAGE_VALIDATION_ERROR_MESSAGES.noFileUploaded)
.refine((file) => file.type.startsWith('image/'), IMAGE_VALIDATION_ERROR_MESSAGES.notAnImage)
.instanceof(File, { message: IMAGE_VALIDATION_ERROR_MESSAGES.noFileUploaded })
.refine((file) => file.size > 0, IMAGE_VALIDATION_ERROR_MESSAGES.fileEmpty)
.refine((file) => file.size <= MAX_FILE_SIZE_MB * 1024 * 1024, {
message: IMAGE_VALIDATION_ERROR_MESSAGES.fileTooLarge
})
.refine(
(file) => {
const fileExtension = file.type.split('/')[1];
return fileExtension ? SUPPORTED_IMAGE_TYPES.includes(fileExtension) : false;
const imageType = file.type.split('/')[1];
return imageType ? SUPPORTED_IMAGE_TYPES.includes(imageType) : false;
},
{
message: IMAGE_VALIDATION_ERROR_MESSAGES.unsupportedImageType
}
)
.refine((file) => file.size <= MAX_FILE_SIZE_MB * 1024 * 1024, {
message: IMAGE_VALIDATION_ERROR_MESSAGES.fileTooLarge
})
});

0 comments on commit 18b9c47

Please sign in to comment.