How to validate if there is an upload file?

Asked

Viewed 767 times

0

I have a form for uploading files:

 @using (Html.BeginForm("importCSV", "Administrador", FormMethod.Post, new { @id = "upldFrm", @enctype = "multipart/form-data" }))
            {
                <div class="form-inline">

                    <input id="file" name="file" type="file" />

                    <input type="button" value="Enviar" id="enviarForm" />

                </div>

                <label style="color:red; white-space: pre-line">@ViewBag.Message</label>
            }

Before it is sent, I would like to validate if the user has even chosen a file through Jquery.
What I got is this:

$("#enviarForm").click(function () {
                var file = $("#file");
                alert(file[0].size);
                if (file[0].size <= 0) {
                    alert("Selecione um arquivo!");
                } else {
                    $("#upldFrm").submit();
                }
            });

But in that case, the size has always returned 20 even without choosing anything. Someone can help me?

1 answer

1


Using the property files of <input/> file this check can be made:

var input = document.querySelector('#file');
console.log(input.files.length);

Example of use:

document.querySelector('form').addEventListener('submit', function(e){
  e.preventDefault();
  if (this.querySelector('#file').files.length > 0) {
    alert('arquivo está selecionado');
  } else {
    alert('arquivo não está selecionado');
  }
}, false);
<form>
<input type="file" name="file" id="file"/>
<br/><input type="submit"/>
</form>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.