input[type=file] validation

2019-02-24 18:13发布

问题:

how can I check if the input file is not empty?

I tried:

$('#image-file').click(function() {
    if ( ! $('#image-file').val() ) {
    alert('Chose a file!');
    return false;
 }
});

but it didn't work.

回答1:

The click event is fired before the value is been set. Rather check it during change event.

$('#image-file').change(function() {
    // ...
});

Or, better, during submitting of the form, because the change won't be fired when the user selected nothing and the field itself was already empty.

$('#form').submit(function() {
    // ...
});