In Builder.io, the input type file does allow you to restrict the formats of the uploaded files using the allowedFileTypes option. However, if you want to limit the size of the images uploaded, you’ll need to handle this validation logic yourself after the file has been selected.
Yes, you can achieve size validation using the onChange event in a couple of ways:
Client-side Validation:
When a file is selected, you can capture the file details through the onChange handler.
Check the file size property (file.size) before allowing further processing.
Example Code:
function handleFileChange(event) {
const file = event.target.files[0];
const fileSizeLimit = 2 * 1024 * 1024; // 2 MB
if (file && file.size > fileSizeLimit) {
alert("The file size should be less than 2 MB");
// Clear the input field or prevent further processing
event.target.value = null;
}
}
Server-side Validation:
You can also perform size validation on the server-side as a second line of defense when the file is uploaded to the server.
While the allowedFileTypes helps with constraining the file format, you do need to handle size constraints in your code either through JavaScript for immediate feedback or on the server-side when handling the uploaded file.