Browse/Upload button Validation using Javascript

Here you can learn how to add client side validation on Browse/Upload button. JQuery helps a lot to add such type of client side validation on HTML DOM.

You can create form like below:

<form method="post" enctype="multipart/form-data" > 
    <input id="browse_button" name="file" type="file">
    <input type="submit" id="upload_file_btn" name="Submit" value="Upload File" />
</form>

 

Now you have to add following jQuery code insideĀ <head> tag.

<script type="text/javascript">
    jQuery('document').ready(function(){
        jQuery('#upload_file_btn').click(function(){
            var browseButtonVal=jQuery('#browse_button').val().length;
            if(browseButtonVal<=0){
                // Write code for what happen if file is not selected
                alert("Please upload file");
                return false;
            }else{
                 // Write code for what happen if file is selected
                return true;
            }
        });
    });
</script>

Note: You have to make sure that jQuery core fileĀ is included in your <head> tag like below:

<script
  src="https://code.jquery.com/jquery-1.12.4.min.js"
  integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
  crossorigin="anonymous"></script>

 

By Ashutosh Pratap

I am software developer by profession and doing work and research in field of Computer programmings like PHP, WordPress, Magento, jQuery, Google APIs and many more web languages. Apart from this I write blogs on programming languages like PHP, Javascript, WordPress etc. I am also individual and independent Freelancer so you can hire me for your web work.

Leave a comment

Your email address will not be published. Required fields are marked *