The following is a demonstration of client-side validation and is implemented to provide a nice user experience. In some cases, client-side validation is a much better method in comparison to the server-side method as it consumes less time.
For instance, if we don’t allow uploading a file more than 4MB or less than 2MB, we could use client-side validation to check that the file the user has chosen follows the given requirements and if it doesn’t, give them a message so they don’t spend all the time uploading the file only to get an error thrown away by the server.
Method 1
- Listen for the change event on the input.
- Check if any file is selected files.length > 0.
- Get the size of the file by files.item(i).size.
- The value will be in bytes. Convert it into any unit as you desire, Megbaytes in this case by Math.round((filesize/1024)).
- Check if the size follows your desired criteria.
The following is a sample code of this first method:
<!DOCTYPE html> <html> <head> <title>File Validation-1</title> </head> <body> <p> <input type="file" id="file" onchange="Filevalidation()" /> </p> <p id="size"></p> </body> <script> Filevalidation = () => { const fi = document.getElementById('file'); // Check if any file is selected. if (fi.files.length > 0) { for (const i = 0; i <= fi.files.length - 1; i++) { const fsize = fi.files.item(i).size; const file = Math.round((fsize / 1024)); // The size of the file. if (file >= 4096) { alert( "File too Big, please select a file less than 4mb"); } else if (file < 2048) { alert( "File too small, please select a file greater than 2mb"); } else { document.getElementById('size').innerHTML = '<b>' + file + '</b> KB'; } } } } </script> </html>
Method 2
In the below example, we will learn how to do the same using jQuery.
- Listen for the change event on the input.
- Get the size of the file by this.files[0].size.
- You can round off the obtained value as well by toFixed() method.
- Check if the size follows your desired criteria.
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>JQuery File Validation <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body> <input id="file" type="file" name="file" /> <p id="output"> <script type="text/javascript"> $('#file').on('change', function() { const size = (this.files[0].size / 1024 / 1024).toFixed(2); if (size > 4 || size < 2) { alert("File must be between the size of 2-4 MB"); } else { $("#output").html('' + 'This file size is: ' + size + " MB" + ''); } }); </script> </body> </html>
Method 3
In this last method, there is a file component with name file, a submit button with value Upload and a div element with id valid_msg.
<html> <body> <form action="uploadAction" method="post" enctype="multipart/form-data" onsubmit="return validation(this)"> <input type="file" name="file"/> <input type="submit" value="Upload"/> <div id="valid_msg"/> </form> </body> </html>
Please note the following points:
- Form’s enctype must be multipart/form-data.
- Form’s method must be post.
- returns statement in onsubmit function.
When the form gets submitted, form’s onsubmit event is called and thus call our validation() function.
function validation(thisform) { with(thisform) { if(validateFileExtension(file, "valid_msg", "pdf/office/image files are only allowed!", new Array("jpg","pdf","jpeg","gif","png","doc","docx","xls","xlsx","ppt","txt")) == false) { return false; } if(validateFileSize(file,1048576, "valid_msg", "Document size should be less than 1MB !")==false) { return false; } } }
The validation function carries a parameter, which is our form’s object. The validation function again calls another two functions with some parameters.
In the first function (validateFileExtension), there are four parameters:
- File object’s name.
- The id of the div component, where the error message will be shown.
- Custom message shown to the user when he tries to upload a file of different extension which does not include in the following array.
- An array which contains some file extension, which means only these extension are allowed when uploading a file. You can easily add or remove extensions to and from this array.
In the second function (validateFileSize), there are again four parameters passed:
- The file component’s name.
- Maximum size of the uploading file; here it given in bytes; 1048576 byte = 1 MB.
- The id of the div component, where the error message will be shown.
- The custom message.
The above said two methods/functions are given below:
function validateFileExtension(component,msg_id,msg,extns) { var flag=0; with(component) { var ext=value.substring(value.lastIndexOf('.')+1); for(i=0;i<extns .length;i++) { if(ext==extns[i]) { flag=0; break; } else { flag=1; } } if(flag!=0) { document.getElementById(msg_id).innerHTML=msg; component.value=""; component.style.backgroundColor="#eab1b1"; component.style.border="thin solid #000000"; component.focus(); return false; } else { return true; } } }
function validateFileSize(component,maxSize,msg_id,msg) { if(navigator.appName=="Microsoft Internet Explorer") { if(component.value) { var oas=new ActiveXObject("Scripting.FileSystemObject"); var e=oas.getFile(component.value); var size=e.size; } } else { if(component.files[0]!=undefined) { size = component.files[0].size; } } if(size!=undefined && size>maxSize) { document.getElementById(msg_id).innerHTML=msg; component.value=""; component.style.backgroundColor="#eab1b1"; component.style.border="thin solid #000000"; component.focus(); return false; } else { return true; } }
The above two functions do the rest. All the major browsers support this.