简体   繁体   English

如何使用javascript制作必填文件字段?

[英]How do I make a file field required using javascript?

I'm trying to make a form with an attachment field(file). 我正在尝试制作一个带有附件字段(文件)的表单。 I want to validate this field. 我要验证此字段。 I know how to do this with PHP, but i'd much rather use javascript to do it. 我知道如何使用PHP来做到这一点,但我宁愿使用JavaScript来做到这一点。 Does anyone know a way to do this? 有人知道这样做的方法吗? I searched around the internet but couldn't find a solution.. 我在互联网上搜索,但找不到解决方案。

This is my file field: 这是我的文件字段:

<input type="file" name="image" id="image" accept="image/*" />

You can try with: 您可以尝试:

<input type="file" name="image" id="image" accept="image/*" required />

And also check with JS: 并使用JS进行检查:

if ( $('#image').is(':empty') ) {
  // empty
}
<input type="file" name="image" id="image" accept="image/*" />

you can check if is valid, like this: 您可以检查是否有效,如下所示:

var file = $('#image').val();
if (file === '') {
      // not valid      
      alert('File is not valid');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM