Check if file input is in file or not

2

I need to do a validation in the file field, if it does not have an attachment, show me a message on the screen, forcing it to attach, I tried some alternatives and I could not.

<div class="form-group" id="inputOculto">
      <input name="arquivo" type="file"  class="form-control-anexo"  input/> 
</div>  

This field only appears if in the subject I select the Work With Us option.

In js it looks like this:

// Contact form com anexo e sem anexo
var form = $('#main-contact-form');
form.submit(function(event){
    event.preventDefault();
    var data;
    var form_status = $('<div class="form_status"></div>');
    data = $("#main-contact-form").serialize();
    $.ajax({
        type: "POST",
        url: $(this).attr('action'),
        data: new FormData(this),
        processData: false,
        contentType: false,
        beforeSend: function(){
            if ($('#mySelect').val() == 'Trabalhe Conosco')
            {
               if ($('#arquivo').val() == null)
               {
                  alert("É Obrigatório Anexar Seu Currículo!" );    
               }
            }
            else
            {
            form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Enviando Mensagem...</p>').fadeIn() );
            }
        }
    }).done(function(data){
        form_status.html('<p class="text-success">Mensagem enviada. O mais breve possível retornaremos o contato.</p>').delay(9000).fadeOut();
    });
});
    
asked by anonymous 06.04.2018 / 16:37

4 answers

1
if ($('#arquivo').files.length === 0) {
   alert("É Obrigatório Anexar Seu Currículo!" )
}
    
06.04.2018 / 17:06
2

If you add the "required" attribute to the input tag, the browser itself will validate the field's requirement:

<div class="form-group" id="inputOculto">
    <input name="arquivo" type="file" class="form-control-anexo" required>
</div>
    
06.04.2018 / 17:13
1

Assign a id and a required attribute to your <input type="file"> and verify that it is valid ... if you do not have a file, it will not be valid.

You can check if the entry is (or is not) valid using validity.valid ... if not then you can post your alert and observe a change event.

var form = $('#main-contact-form');
let file = document.getElementById('fileupload')
form.submit(function(event){
    event.preventDefault()
    $.ajax({
        type: "POST",
        url: $(this).attr('action'),
        data: new FormData(this),
        processData: false,
        contentType: false,
        beforeSend: function(){
            if ( file.validity.valid ) {
                //... ok [send]
            } else {
                // observe file change
                file.addEventListener('change', function(evt) {
                    if ( evt.target.result.length > 0 ) {
                        //... ok
                    }
                })
            }
        }
    }).done(function(data)  {
        //...
    })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formid="main-contact-form" action="#">
    <div class="form-group" id="inputOculto">
        <input id="fileupload" name="arquivo" type="file" required> 
    </div>
    <button type="submit">Enviar</button>
</form>

You can also define the file type with the accept="" attribute

    
06.04.2018 / 17:10
0

You have problems with your code:

Syntax error in input :

<input name="arquivo" type="file"  class="form-control-anexo"  input/>
                                                                 ↑

The correct one would be:

<input name="arquivo" type="file" class="form-control-anexo">

You are calling the file field by a id that does not exist:

if ($('#arquivo').val() == null)
          ↑

You could insert a id into the file field, but it is not necessary because you can get name :

if ($('input[name="arquivo"]').val() == null)

But you can still do it this way:

if(!$('input[name="arquivo"]').val()){

The ! will return true if the file field is empty.

Example:

var form = $('#main-contact-form');
form.submit(function(event){
   event.preventDefault();
   if(!$('input[name="arquivo"]').val()){
      alert("É Obrigatório Anexar Seu Currículo!" );
   }else{
      alert("Arquivo anexado!" );
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formid="main-contact-form">
<input name="arquivo" type="file" class="form-control-anexo" />
<br>
<button>Enviar</button>
</form>
    
06.04.2018 / 17:24