Checking file type using Javascript
I have a question regarding JavaScript validation. I check <input type="file"> when my scripts run, it checks, but the action page is also called. I want to stop the action page until validation is complete. Here is my code, any help would be awesome. Relations
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Image Uploading</title> </head> <body> <form name="xx" action="server.php" method="post" enctype="multipart/form-data" onsubmit="Checkfiles(this)"> <input type="file" name="file_uploading" id="filename"> <input type="submit" value="Submit" name="uploadfile"> </form> <form name="view" method="post"> <a href="view_server.php">View your uploaded Images</a> </form> </body> </html> <script type="text/javascript"> function Checkfiles() { var fup = document.getElementById('filename'); var fileName = fup.value; var ext = fileName.substring(fileName.lastIndexOf('.') + 1); if(ext =="GIF" || ext=="gif") { return true; } else { alert("Upload Gif Images only"); return false; } } </script> You can use File Api to check the magic number . Perhaps look at this answer for other validation ideas. More reliable than checking the file extension.
Checking file extension using javascript
function ValidateExtension() { var allowedFiles = [".doc", ".docx", ".pdf"]; var fileUpload = document.getElementById("fileUpload"); var lblError = document.getElementById("lblError"); var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$"); if (!regex.test(fileUpload.value.toLowerCase())) { lblError.innerHTML = "Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only."; return false; } lblError.innerHTML = ""; return true; } the onclick submit button event calls this javascript function.
Use ID = lblError to print the error message in the html section.
var _URL = window.URL || window.webkitURL; $("input[type=file]").change(function(e) { var file; if ((file = this.files[0])) { var img = new Image(); img.onload = function () { // do to on load }; img.onerror = function () { alert("valid format " + file.type); }; img.src = _URL.createObjectURL(file); } });