javascript 如何使文件上传字段成为必填字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23949148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:52:19  来源:igfitidea点击:

How to make file upload field mandatory

javascriptjqueryvalidation

提问by user3367831

Hello can anyone plz fix this problem.

你好任何人都可以解决这个问题。

my input field is below code and I am doing validation on form submit i.eis:

我的输入字段在代码下方,我正在对表单提交 i.eis 进行验证:

<input name="file[]" type="file" multiple="multiple">

<form name="bdmrequest" enctype="multipart/form-data" method="post"  action="<?php echo $_SERVER["PHP_SELF"];?>" onsubmit="return(validate());">

i have included validate.js in header and i am able to do validation of other fields except file upload. validation code i am using:

我在标题中包含了 validate.js 并且我能够验证除文件上传之外的其他字段。我正在使用的验证代码:

if(document.bdmrequest.file.value== "")
  {
   alert("Attachment Required");
   document.bdmrequest.file.focus();
    return false;
  } 

js doesn't support me to use (document.bdmrequest.file[].value== "") please suggest me the alternatives. the name of my input type has to be file[] only.

js 不支持我使用 (document.bdmrequest.file[].value== "") 请给我建议替代方案。我的输入类型的名称只能是 file[]。

回答by Shaunak D

If you need pure Javascript: Demo Fiddle

如果您需要纯 Javascript:演示小提琴

function validate(){
    var inp = document.getElementById('upload');
    if(inp.files.length === 0){
        alert("Attachment Required");
        inp.focus();

        return false;
    }
}

jQuery:

jQuery:

function validate(){

    if($('#upload')[0].files.length === 0){
        alert("Attachment Required");
        $('#upload').focus();

        return false;
    }
}

回答by Dileep Kumar

No need of JavaScript validation you can use "required" attribute in input type....

无需 JavaScript 验证,您可以在输入类型中使用“required”属性....

 <input type="file" required="required">

回答by Alex Char

You can check if the value is empty.

您可以检查该值是否为空。

<input name="file[]" type="file" multiple="multiple" id="uploadField">

And then in js:

然后在js中:

if($("#uploadField").val() != ""){
      //your success code here
}