Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to validate file extension and size before upload?

    • 0
    • 2
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 9.03k
    Comment on it

    Here is the example to validate the file extension and size before upload. Regular expression has been used to validate the file extension. And to validate file size, we use size property of file input i.e., img.files[0].size. Onclick event of button, validate() function is being called. First, it checks for file extensions (jpg, jpeg, png, etc) and give error message for the files having other extensions. Then, it validates the file size by calculating the file size using img.files[0].size.

    Example:

    <html>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
    function Validate()
    {
         var image =document.getElementById("image").value;
         if(image!='')
         {
               var checkimg = image.toLowerCase();
              if (!checkimg.match(/(\.jpg|\.png|\.JPG|\.PNG|\.jpeg|\.JPEG|\.mp4|\.MP4|\.flv|\.FLV|\.mkv|\.MKV)$/)){ // validation of file extension using regular expression before file upload
                  document.getElementById("image").focus();
                  document.getElementById("errorName5").innerHTML="Wrong file selected"; 
                  return false;
               }
    
                var img = document.getElementById("image"); 
                alert(img.files[0].size);
                if(img.files[0].size <  1048576)  // validation according to file size
                {
    
                document.getElementById("errorName5").innerHTML="Image size too short";
                return false;
                 }
                 return true;
          }
    
    }
    </script>
    <body>
    <form action="" method="post"  onSubmit="return Validate()";>
    <input type="file" id="image"/>
    <span id="errorName5" style="color: red;"></span>
    <input type="submit" value="Upload" />
    </form>
    </body>
    </html>
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: