Check if input file is with file or not

Asked

Viewed 3,601 times

2

I need to do a validation in the field file, in case it has no attachment show me a message on the screen forcing to attach, I tried some alternatives and 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 option Work with us.

No js this so:

// 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();
    });
});

4 answers

1


if ($('#arquivo').files.length === 0) {
   alert("É Obrigatório Anexar Seu Currículo!" )
}

1

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

You can check whether the input is (or not) valid using validity.valid...if it is not then you can launch 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>


<form id="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 set the file type with the attributo accept=""

1

If you add the attribute "required" to the input tag, the browser itself will already validate the mandatory field:

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

0

You have trouble with your code:

Syntax error in input:

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

The right thing would be:

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

You’re calling the field file by a id that doesn’t exist:

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

You could insert a id to the countryside file, but it’s not necessary because you can pick up by the name:

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

But you can still do it this way:

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

The ! will return true case the field file be 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>
<form id="main-contact-form">
<input name="arquivo" type="file" class="form-control-anexo" />
<br>
<button>Enviar</button>
</form>

  • Thank you very much, it worked perfectly.

  • Not at all, friend! If you think the answer is better, you can mark and/or give a positive vote if you wish. Obg!

Browser other questions tagged

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