我想强制(一个 HTML)“文件”输入元素:类似于
<input type='file' required = 'required' .../>
但它不起作用。
我看到了这本WW3手册,其中指出“必需”属性是 HTML 5 的新特性。但我没有在我正在工作的项目中使用 HTML 5,它不支持新功能。
任何想法?
多亏了 HTML5,它就这么简单:
<input type='file' required />
例子:
<form>
<input type='file' required />
<button type="submit"> Submit </button>
</form>
你可以像这样使用 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" />
您可以创建一个在表单提交上执行的 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. */
}
});
});
此脚本等待表单提交,然后循环通过每个具有该required
属性的表单元素输入一个值。如果一切都有一个值,它会提交表单。
要检查的示例元素可能是:
<input type="file" name="file_input" required="true" />
(在您的网站上使用此代码时,您可以删除评论并缩小此代码)
有时输入字段未与表单绑定。我可能看起来在<form> and </form>
标签内,但它在这些标签之外。
您可以尝试将表单属性应用于输入字段,以确保它与您的表单相关。
<input type="file" name="" required="" form="YOUR-FORM-ID-HERE" />
我希望它有所帮助。
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>
以上所有陈述都是完全正确的。但是,恶意用户可能会在不使用您的表单的情况下发送 POST 请求以生成错误。因此,HTML 和 JS 虽然提供了一种用户友好的方法,但不会阻止此类攻击。为此,请确保您的服务器仔细检查请求数据以确保没有任何内容为空。