简体   繁体   中英

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. 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:

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');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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