1

您好我需要验证file输入类型:

<form onsubmit="return validate()">
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="submit" name="BtnSubmit" value="save" />
</form>

我创建的 j 查询方法是

 function validate()
 {
    $(".multi").each(function(){
       var files = $(this).val(); 

       if(files=='')
       { 
          alert("No document file selected");
          return false; 
       }
    });
 }

问题是它显示警报但表单正在提交。

4

3 回答 3

1

Kindly see code snippet below for validating if file submitted is a valid file type. As well as checking if a file was submitted to start with.

//Javascript

$("#btnUpload").click(function (e) {

        var file = $("#fileupload").val();  //Fetch the filename of the submitted file

        if (file == '') {    //Check if a file was selected
            //Place warning text below the upload control
            $(".errorDiv").html("Please select a file first.");
            e.preventDefault();
        }
        else {
            //Check file extension
            var ext = file.split('.').pop().toLowerCase();   //Check file extension if valid or expected
            if ($.inArray(ext, ['txt']) == -1) {
                $(".errorDiv").html("Select valid text file (txt).");
                e.preventDefault(); //Prevent submission of form
            }
            else {
        //Do your logic here, file upload, stream. etc.. if file was successfully validated
        }
    }
});

//For the HTML

<input id="fileupload"     type="file" name="files[]" /><br />
                    <p class="reminder"> Allowed file type: .txt</p>
                    <div class="errorDiv"></div>
                    <input type="button" id="btnUpload" value="Upload File"/><br />

Heads up: Perform file validation on the server side as well to prevent back-end error or data injections.

I hope this helps!

于 2013-02-11T14:41:32.820 回答
1
function validate(){
  $(".multi").each(function(){
   var files = $(this).val(); 
   if(files==''){ 
     alert("No document file selected"); 
   }
   return false;       
 });
}

您的 return 语句应该在不同的块中,而不是相同的 if 块,因此它将像 else 一样工作

于 2013-02-11T14:33:04.323 回答
0

问题是,您为每个循环返回 false 。如果在$.each()循环内返回 false,则意味着退出$.each循环。所以这里会出现警报,然后它会简单地退出每个。

您可以通过多种方式完成该任务。但最简单的方法是带一个标志变量。

function validate() {
    $check = true;
    $(".multi").each(function(){
       var files = $(this).val(); 

        if(files=='') { 
           alert("No document file selected");
           $check = false;
           return false; // You don't want to loop, so exit each loop
        }
    });

    return $check;
}
于 2014-01-24T04:18:26.307 回答