If you have a file upload in a form it is helpful to limit what formats you want to allow users to upload. This tutorial will show you how to do this using javascript. Please note that client side validation is useful, but can be easily bypassed. For safest results use both client and server side validation.
For this example we will create a function called checkExtension(). This function will check the extension of the file to ensure that it is a format that you want to allow. If it is an allowed format it will do nothing and if it isn’t it will alert the user then clear the file upload input. The allowedExtensions variable is where you will put a list of the extensions that you want to allow.
var allowedExtensions = { '.zip' : 1, '.rar' :1 }; function checkExtension(filename) { var match = /\..+$/; var ext = filename.match(match); if (allowedExtensions[ext]) { return true; } else { alert("File must be .zip or .rar!"); //will clear the file input box. location.reload(); return false; } }
This is all that is required from javascript to enable the validation. All you need to do is create the html form and add the onchange event handler to make it call this function.
<form> <input type="file" name="file" onchange="checkExtension(this.value);"/> </form>
Remember to also include server side validation to ensure you are fully protected.
Simple and very util Thanks