How to validation input type="file" #1946
-
I read this document https://react-hook-form.com/get-started#Applyvalidation not see example validate file upload For example file name , max file size, type file don't have this feature ? or something I missed 😷😷 |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments 8 replies
-
U will have to use validate function to measure the size of ur file, for required field required still works. |
Beta Was this translation helpful? Give feedback.
-
How can I add the validation for image size, image type, and display alert message if it is not suitable?
|
Beta Was this translation helpful? Give feedback.
-
If you are wondering how to do this using just react hook form you can use the validate function. Here is my implementation of this validation: {...register('image', {
validate: {
lessThan10MB: files => files[0]?.size < 10000000 || 'Max 10MB',
acceptedFormats: files =>
['image/jpeg', 'image/png', 'image/gif'].includes(
files[0]?.type
) || 'Only PNG, JPEG e GIF',
},
})} And if you are wondering whats inside files this is the answer so you can do name validation and stuff |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
-
There is a problem with this approach: You need to use a custom handle function to process from the file path to a file object itself, but doing that you will need to leave the input value out to avoid this problem. But by avoiding passing the value to the controlled input, we can not reset it using the That's a big problem when we have a static form, for instance. |
Beta Was this translation helpful? Give feedback.
-
This worked for me: ref={register({
required: 'File is required',
validate: (value) => {
const acceptedFormats = ['pdf']; // Add more file formats if needed
const fileExtension = value[0]?.name.split('.').pop().toLowerCase();
if (!acceptedFormats.includes(fileExtension)) {
return 'Invalid file format. Only PDF files are allowed.';
}
return true;
}
})} |
Beta Was this translation helpful? Give feedback.
U will have to use validate function to measure the size of ur file, for required field required still works.