How to implement validation for input type file using jQuery or javascript?


Hello, I have a HTML form inside which there is <input type="file" /> field, and now before posting form to the server side, I need to validate/check if file field is empty or not, I want user to upload atleast one image file in this field, so how I can implement validation message for <input type ="file" /> field in the form using jQuery or javascript code?

Sample HTML Form

<form action="/URL" method="post" name="value" enctype="multipart/form-data">
    <div><h3 class="page-title">Upload a New Invoice</h3></div>
    <div >
       
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 m-t-10">
         <input type="file" name="file" id="file"  />
            
           
            
          
            <div class="">
                <div class="editor-field">
                    <input type="submit" value="Create" class="btn btn-success " />
                </div>
            </div>
        </div>
    </div>
        </div>
</form>

Any Link or code would help, thank you.


Asked by:- jon
3
: 7168 At:- 6/27/2018 8:59:35 AM
HTML Javascript file input validation







2 Answers
profileImage Answered by:- jaya

There are various ways to validate file input using javascript/jQuery

  1. You can simply validate by checking $("#FileInput").val() == ""
    if($("#FileInput").val() == "")
    {
      //alert value cannot be null
    }?
  2. Using jQuery Validate plugin
    $.validator.addMethod('filesize', function(value, element, param) {
       return this.optional(element) || (element.files[0].size <= param) 
    });    
    
    $('#form').validate({
            rules: {
                firstname: {
                    minlength: 6,
                    required: true
                },
    
                file: {
                    required: true, 
                    extension: "png|jpeg|jpg",
                    filesize: 1048576,   
                }
            },
            messages: 
               { 
                file: "File must be JPEG or PNG, less than 1MB" 
               },
            highlight: function(element) {
                $(element).closest('.form-group').addClass('has-error');
            },
            unhighlight: function(element) {
                $(element).closest('.form-group').removeClass('has-error');
            },
           
            errorPlacement: function(error, element) {
                if(element.parent('.input-group').length) {
                    error.insertAfter(element.parent());
                } else {
                    error.insertAfter(element);
                }
            }
        });
    ?

    HTML of above Code can be as below

    <form id="form" enctype="multipart/form-data">
        <div class="form-group">
            <label class="control-label" for="firstname">First:</label>
            <div class="input-group">
                <input class="form-control"  name="firstname" type="text" />
            </div>
        </div>        
        
            <div class="form-group">
            <label class="control-label" for="file">Image:</label>
            <div class="input-group">
                <input  id="file" name="file" type="file" />
            </div>
        </div>
        
        
            <button type="submit" class="btn btn-primary">Submit</button>
    </form>
  3. using jQuery to place the required attribute in all input type="file" fields of the page
    $('input[name^="fileupload"]').each(function () {
        $(this).rules('add', {
            required: true,
            accept: "image/jpeg, image/png"
        })
    })?

    Fiddle link

Anyone of the above solution should work.

3
At:- 6/30/2018 8:50:21 AM Updated at:- 9/27/2022 7:39:08 AM
Thank you, jQuery validate (2) solution works for me to validate fie input as I was already using jQuery validate plugin so used it. 0
By : jon - at :- 7/9/2018 11:34:15 AM


profileImage Answered by:- bhanu

Above solution is excellent, but if you want to validate input and check file size at same time, here is custom jquery validation function for it

function validate()
{
  var file = $('#file').val(); 

  if (file == "") {  
    alert("select file"); //alert when no file is selected
    return false;          
  }
  else
  { 
     /* get file size in MB */  
     var file_size = $('#file')[0].files[0].size / 1024 / 1024; 

     //check if file size is greater than 2MB
     if(file_size > 2) {  
       alert("File size is greater than 2MB"); return false; 
     }
     else
     {
       //submit form
     }
  } 

}

Here is the working fiddle https://jsfiddle.net/g6wstmkz/

Thanks

1
At:- 9/18/2021 3:08:22 PM
Thanks for the pure Javascript based input type file validation check. 0
By : vikas_jk - at :- 9/27/2022 11:02:39 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use