How to make a mandatory input file?

0

Cordial Greeting,

I hope you can help me, what I want to do is make mandatory a "file" type input.

<form method="POST"  id="frm_contact" name="frm_contact" enctype="multipart/form-data">
    <input type="file" id="1" name="1" class="form-control-file">
     <input type="submit" class="btn btn-primary" id="enviardoc" value="Enviar Documentos">
</form>

Since I capture it and send it through AJAX, but I want it to be mandatory.

<script type="text/javascript">
   $(function(){
                      $("#frm_contact").on("submit", function(e){
                          e.preventDefault();
                          var f = $(this);
                          var formData = new FormData(document.getElementById("frm_contact"));

                          $.ajax({
                              url: "DocumentosApro.php",
                              type: "POST",
                              dataType: "html",
                              data: formData,datos,
                              cache: false,
                              contentType: false,
                              processData: false
                          })
                              .done(function(res){
                                  alert(res);
                                  location.reload();

                              });
                      });

                    }); 
</script>

It should be noted that the file is sent well, it does not load a file, it does the function, but I want it to be obligatory ..

Thanks

    
asked by Andres Rodriguez 16.11.2018 в 16:00
source

2 answers

2

I leave a functional example, it is true that you can add the attribute of HTML required , but if you want a little more security you can validate from Javascript, try this.

$(function() {
  $("#frm_contact").on("submit", function(e) {
    e.preventDefault();
    
    /*Con el id del input tipo file le indicas que lea la longitud o cantidad de 
      archivos que se seleccionaron*/
    var vidFileLength = $("#uploadFile")[0].files.length;

    /*Aquí validas si no han seleccionado archivos mandas una alerta y se detiene el 
     script*/
    if (vidFileLength === 0) {
      alert("No hay archivos, para enviar.");
     return false;
    }
    var f = $(this);
    var formData = new FormData(document.getElementById("frm_contact"));

    $.ajax({
        url: "DocumentosApro.php",
        type: "POST",
        dataType: "html",
        data: formData,
        datos,
        cache: false,
        contentType: false,
        processData: false
      })
      .done(function(res) {
        alert(res);
        location.reload();

      });
  });

});
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

<form method="POST" id="frm_contact" name="frm_contact" enctype="multipart/form-data">
  <input id="uploadFile" name="uploadFile" type="file" id="1" name="1" class="form-control-file">
  <input type="submit" class="btn btn-primary" id="enviardoc" value="Enviar Documentos">
</form>

In the same way, it is always important to perform validation from the server side. Greetings.

    
answered by 16.11.2018 / 16:22
source
0

I share a small fragment of HTML to you to see how to apply what you comment, but before a bit of theory:

  • To achieve what you need, the required attribute is a boolean attribute that solves your problem. When present, it specifies that a field of entry before sending the form.
    Consider the following: It works with the following types of input: text, search, url, phone, email, password, selectors of date, number, check box, radio and file.

When you enter the input tag, you add the required attribute that I described earlier.

<!DOCTYPE html>
<html>
<body>

<form action="/action_page.php">
  Username: <input type="text" name="usrname" required>
  <input type="submit">
</form>


</body>
</html>

Also, it is recommended that the validations be done in your JS or JQuery for security, I share an example of its application:

function Jq(){
  console.log();
    if ($('#txtrut').val() == "") {
        alert('¡Vacío!');
        return false;
    }else{
      alert('¡Completo!');
      
    }
};

function Js(){
 valor = document.getElementById("txtrut1").value;
 if( valor != "" ) {
  alert('¡Completo!');
 }else{
   alert('¡Vacío!');
 }
}
<!-- Validación con Libreria JQuery --> 
<script     src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<label>Validación con JQuery</label>
<br>
<input type="text" id="txtrut" >
<button onclick="Jq();">Validate</button>

<!-- Validacion con javascript -->
<br>
<label>Validación con Javascript</label>
<br>
<input type="text" id="txtrut1" >
<button onclick="Js();">Validate</button>

I hope I help you,

Good luck ...

    
answered by 16.11.2018 в 16:06