validate form input type file type using jquery validate plugin

30,009

Solution 1

Try this.

$(document).ready(function() {
    $("#formElem").validate({
        rules: {  
            dimage:{
                required: true    
            }  
        },
        messages: {
            dimage:{
               required: 'Please select the image!'  
            } ,
        }       
    });
});

Solution 2

If your uploading an image file Jquery Validation plugin have a option accept you can set that to a value which will validate that if the file is really an image then your jquery code will be like this:

$("#formElem").validate({

      rules: {  

            dimage:{
                    required: true,
                    accept:"jpg,png,jpeg,gif"
                }  
        },
    messages: {

            dimage:{
                    required: "Select Image",
                    accept: "Only image type jpg/png/jpeg/gif is allowed"
                }  

             }      
        });

for more information See Official Docs

Share:
30,009
MAK
Author by

MAK

Updated on July 09, 2022

Comments

  • MAK
    MAK almost 2 years

    the following code: script code

    <script type="text/javascript">
    $(document).ready(function() {
        $("#formElem").validate({
    
            rules: {  
    
                dimage:{
                    minlength:200    
                }  
            },
    messages: {
    
    
                 dimage:{
                   required: 'Please select the image!'  
                } ,
    
            }       
        });
    
    });
    </script>
    

    html code

    <form id="formElem" name="formElem" action="" method="post">
    
     <input type="file" name="dimage" id="dimage" />
    </form>
    

    I'm using jquery validate.js file for client side validation. when i create a file with above code it's not showing any error message.

    How should i alert the error message when the user not selected the file?