How I know if my input type=“file” has content selected

前端 未结 3 1786
囚心锁ツ
囚心锁ツ 2021-02-05 05:51

i have a simple input file but I\'m trying to validate after the post if the input file has content.

I

3条回答
  •  盖世英雄少女心
    2021-02-05 06:20

    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:

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

    
    

    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:

    
    

    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.

提交回复
热议问题