26

i have a simple input file <input type="file" name="file" id="file"> but I'm trying to validate after the post if the input file has content.

I trying with $("#file").val() but, the dom of the controls is the same always.

3
  • Where is your code.! I cant see it.! Commented Apr 20, 2013 at 21:15
  • No, checking before you post if that file exists will work fine with if($('#file').val()).
    – Ohgodwhy
    Commented Apr 20, 2013 at 21:16
  • 2
    if you really have <input type="file" id="file" />, then $("#file").val() give you the value...
    – RafH
    Commented Apr 20, 2013 at 21:16

3 Answers 3

41

What do you mean by: after the post, do you mean:

-After clicking on a submit button but before posting or submitting?

-Or you mean after it has been submitted and the content has reached the server?

If it is the first case, make sure to return false to the form so it doesn't submit, and you can validate, for example:

<form onsubmit="return false">

or try to return a boolean to the form after calling a validation function on submit:

<form onsubmit="return validate()">

Then using Jquery validate your data:

function validate(){

  valid = true;

     if($("#file").val() == ''){
         // your validation error action
        valid = false;

     }

    return valid //true or false
}

if you find errors return false, if the data is valid return true. After understanding how it works, ultimately, all of this can be done with Jquery:

HTML:

<form id="fileform" action="nextpage.php">

JS:

$('#fileform').submit(function(){
     valid = true;

     if($("#file").val() == ''){
        // your error validation action
        valid =  false;
    }

    return valid
});

Also, if you are checking to see what type of file is being submitted, you can check this post: jQuery - INPUT type=File , Image FileType Validation options?

If what you want to do is validate the data AFTER submitting then you have to code the validation in a server scripting language like PHP.

5

try to get the value after the form submission like this

$('#yourform').submit(function(){
     var val = $("#file").val();
    if(val == ''){
       return false;
    }
});
4

trying to validate after the post

This would be something you would do server-side not on the client via jQuery. If you tag your question with the server-side language you're using we can then provide you with the help you need.

Not the answer you're looking for? Browse other questions tagged or ask your own question.