Html 强制“文件”输入元素(必需)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17649479/
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-08-29 11:09:27  来源:igfitidea点击:

Making 'file' input element mandatory (required)

htmlcss

提问by Bere

I want to make (an HTML) 'file' input element mandatory: something like

我想让(一个 HTML)'file' 输入元素成为强制性的:像

<input type='file' required = 'required' .../>

But it is not working.

但它不起作用。

I saw this WW3manual which states 'required' attribute is new to HTML 5. But I am not using HTML 5 in the project I am working which doesn't support the new feature.

我看到了这份WW3手册,其中指出“必需”属性是 HTML 5 的新属性。但我没有在我正在工作的项目中使用不支持新功能的 HTML 5。

Any idea?

任何的想法?

回答by Ibo

Thanks to HTML5, it is as easy as this:

多亏了 HTML5,它就像这样简单:

<input type='file' required />

Example:

例子:

<form>
  <input type='file' required />
  <button type="submit"> Submit </button>
</form>

回答by Vivek Sadh

You can do it using Jquery like this:-

您可以像这样使用 Jquery 来做到这一点:-

<script type="text/javascript">
$(document).ready(function() {
    $('#upload').bind("click",function() 
    { 
        var imgVal = $('#uploadfile').val(); 
        if(imgVal=='') 
        { 
            alert("empty input file"); 
            return false; 
        } 


    }); 
});
</script> 

<input type="file" name="image" id="uploadfile" size="30" /> 
<input type="submit" name="upload" id="upload"  class="send_upload" value="upload" />

回答by Kaushik Singh

As of now in 2017, I am able to do this-

截至2017年,我能够做到这一点-

<input type='file' required />

and when you submit the form, it asks for file. Screenshot on Google Chrome

当您提交表格时,它会要求您提供文件。 Google Chrome 上的屏幕截图

回答by Rob Farr

You could create a polyfill that executes on the form submit. For example:

您可以创建一个在表单提交上执行的 polyfill。例如:

/* Attach the form event when jQuery loads. */
$(document).ready(function(e){

/* Handle any form's submit event. */
    $("form").submit(function(e){

        e.preventDefault();                 /* Stop the form from submitting immediately. */
        var continueInvoke = true;          /* Variable used to avoid $(this) scope confusion with .each() function. */

        /* Loop through each form element that has the required="" attribute. */
        $("form input[required]").each(function(){

            /* If the element has no value. */
            if($(this).val() == ""){
                continueInvoke = false;     /* Set the variable to false, to indicate that the form should not be submited. */
            }

        });

        /* Read the variable. Detect any items with no value. */
        if(continueInvoke == true){
            $(this).submit();               /* Submit the form. */
        }

    });

});

This script waits for the form to be submitted, then loops though each form element that has the requiredattribute has a value entered. If everything has a value, it submits the form.

该脚本等待表单提交,然后循环遍历每个具有该required属性的表单元素都输入了一个值。如果所有东西都有值,它就会提交表单。

An example element to be checked could be:

要检查的示例元素可以是:

<input type="file" name="file_input" required="true" />

(You can remove the comments & minify this code when using it on your website)

(在您的网站上使用时,您可以删除评论并缩小此代码)

回答by otinanai

var imgVal = $('[type=file]').val(); 

Similar to Vivek's suggestion, but now you have a more generic selector of the input file and you don't rely on specific ID or class.

与 Vivek 的建议类似,但现在您有一个更通用的输入文件选择器,并且您不依赖于特定的 ID 或类。

See this demo.

请参阅此演示

回答by Isaac Krementsov

All statements above are entirely correct. However, it is possible for a malicious user to send a POST request without using your form in order to generate errors. Thus, HTML and JS, while offering a user-friendly approach, will not prevent these sorts of attacks. To do so, make sure that your server double checks request data to make sure nothing is empty.

以上所有陈述都是完全正确的。但是,恶意用户可能会在不使用您的表单的情况下发送 POST 请求以产生错误。因此,HTML 和 JS 虽然提供了一种用户友好的方法,但不会阻止此类攻击。为此,请确保您的服务器仔细检查请求数据以确保没有任何内容为空。

回答by Nomi

Some times the input field is not bound with the form. I might seem within the <form> and </form>tags but it is outside these tags.

有时输入字段不与表单绑定。我可能看起来在<form> and </form>标签内,但它在这些标签之外。

You can try applying the form attribute to the input field to make sure it is related to your form.

您可以尝试将表单属性应用于输入字段以确保它与您的表单相关。

<input type="file" name="" required=""  form="YOUR-FORM-ID-HERE"  />

I hope it helps.

我希望它有帮助。

回答by Shahab Ghannadzadeh

https://www.geeksforgeeks.org/form-required-attribute-with-a-custom-validation-message-in-html5/

https://www.geeksforgeeks.org/form-required-attribute-with-a-custom-validation-message-in-html5/

<button onclick="myFunction()">Try it</button> 


<p id="geeks"></p> 

<script> 
    function myFunction() { 
        var inpObj = document.getElementById("gfg"); 
        if (!inpObj.checkValidity()) { 
            document.getElementById("geeks") 
                    .innerHTML = inpObj.validationMessage; 
        } else { 
            document.getElementById("geeks") 
                    .innerHTML = "Input is ALL RIGHT"; 
        } 
    } 
</script>