Simple Image Validation Using JavaScript

In this tutorial we will create a Simple Image Validation Using JavaScript. This project is compose of Javascript and PHP. This project shows you how to validate an image file using a javascript function, every image file that the user uploaded it will save or copy automatically in the directory folder. Each image that the user upload a photo has a time stamp to determine the new file name.

Sample Code

PHP Function for uploading an image file and copying to the directory folder.
  1. <?php
  2. if(isset($_POST['submit']))
  3. {
  4. $current_img=$_FILES['img_file']['name'];
  5. $extension = substr(strrchr($current_img, '.'), 1);
  6. if (($extension!= "jpg") && ($extension != "jpeg") && ($extension != "gif") && ($extension != "png") && ($extension != "bmp"))
  7. {
  8. die('Unknown Extension');
  9. }
  10. $time = date("pYhis");
  11. $new_img = $time . "." . $extension;
  12. $destination="uploads/".$new_img;
  13. $action = copy($_FILES['img_file']['tmp_name'], $destination);
  14. if (!$action)
  15. {
  16. die('File Image Copy Failed!!!');
  17. }
  18. else
  19. {
  20. echo "<form align='center'>";
  21. echo "File Image Copy Successfully...";
  22. echo "<a href='index.php'>&nbsp; Back</a>";
  23. echo "</form>";
  24. }
  25. }
  26. else
  27. {
  28. ?>
  29. <body align="center">
  30. <form name="form" action="" enctype="multipart/form-data" method="post" onSubmit="return validate();">
  31. <h2>Upload Image</h2>
  32. <br />
  33. Upload An Image <input type="file" name="img_file"> <input type="submit" name="submit" value="Upload">
  34. </form>
  35. </body>
  36. <?php
  37. }
  38. ?>
Javascript Function for image validation format.
  1. <script language="javascript">
  2. function validate()
  3. {
  4. var extensions = new Array("jpg","jpeg","gif","png","bmp");
  5. var img_file = document.form.img_file.value;
  6. var img_length = document.form.img_file.value.length;
  7. var pos = img_file.lastIndexOf('.') + 1;
  8. var ext = img_file.substring(pos, img_length);
  9. var final_ext = ext.toLowerCase();
  10. for (i = 0; i < extensions.length; i++)
  11. {
  12. if(extensions[i] == final_ext)
  13. {
  14. return true;
  15. }
  16. }
  17. alert("Upload An Image File With One Of The Following Extensions "+ extensions.join(', ') +".");
  18. return false;
  19. }
  20. </script>
Hope that you learn in this tutorial. And for more updates and programming tutorials don't hesitate to ask and we will answer your questions and suggestions. Don't forget to LIKE & SHARE this website.

Add new comment