0

want to get a validation script to validate the file upload box onsubmit.

check the extension of the file and validate accordingly to the extension of file loaded

3 Answers 3

2

Check here: http://jsfiddle.net/uh2Gn/

HTML:

<form method="post" enctype="" onsubmit="return validate()"> <input type="file" id="file" /> <input type="submit" /> </form> 

JavaScript:

function validate() { var filename=document.getElementById('file').value; var extension=filename.substr(filename.lastIndexOf('.')+1).toLowerCase(); //alert(extension); if(extension=='jpg' || extension=='gif') { return true; } else { alert('Not Allowed Extension!'); return false; } } 

Keep in mind that this is only for user convenience, that he doesn't go theu a long submit process to get an error at the server, cuz for sure you must implement a check at server-side.

Sign up to request clarification or add additional context in comments.

Comments

1

If you don't mind jquery, then you can use the validation plugin, which is available here. A brief introduction and small demo is available here.

1 Comment

sorry, most of my form <input> is done validated wih javascript..the only remaining part is the file upload box..no worries...thanks for you answers, I would rather try use it for my another module
0

I use the following in my php script for validation.

$status_file = validate_and_upload("project_file"); function validate_and_upload($input_tag_name) { $allowedExts = array("gif", "jpeg", "jpg", "png", "ppt", "doc", "pdf", "xls", "xlxs", "txt", "docx"); $filename = $_FILES[$input_tag_name]['name']; if ( !$filename ) return 0; $extension = pathinfo($filename, PATHINFO_EXTENSION); if ( ($_FILES[$input_tag_name]["size"] < 33554432) && in_array($extension, $allowedExts) ) // 33554432 is 32.00 MB { if ($_FILES[$input_tag_name]["error"] > 0) { echo "Return Code: " . $_FILES[$input_tag_name]["error"] . "<br>"; return -1; } else { if (file_exists("/sites/default/files/private/" . $_FILES[$input_tag_name]["name"])) { echo $_FILES[$input_tag_name]["name"] . " already exists. "; return 2; } else { $hard_disk_upload_directory = "C://xampp/htdocs/mywebsite/sites/default/files/private/"; if (move_uploaded_file($_FILES[$input_tag_name]["tmp_name"], $hard_disk_upload_directory . $_FILES[$input_tag_name]["name"])) return 1; else return -1; } } } else { echo "<script>alert('Invalid file'); window.location.href='http://mywebsite/home';</script>"; return -1; } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.