Validation in multiple input file with JS

Asked

Viewed 839 times

1

Guys I have a JS code for validation of the form attachments and I’m trying to call the function once for all fields with the same class="" the problem is that it works only with the first view the same field in the other views does not pass the validation, follows the codes.

validates.js //function called in include header.php

function verifica_extensao()
      {
      var arquivo = $(".input_anexo").val();

      var extensoes_permitidas = new Array(".jpg", ".jpeg", ".png", ".gif", ".pdf", ".php", ".js", ".swf", ".zip", ".rar", ".bmp", ".css", ".html", ".txt", ".doc", ".docx", ".word", ".7zip");
      var erro = "";
      if ($.trim(arquivo)=="")
      {
        return true;
      }
      else
      {
          var extensao = (arquivo.substring(arquivo.lastIndexOf("."))).toLowerCase();
          var permitida = false;
          for (var i = 0; i < extensoes_permitidas.length; i++) 
          {
            console.log("if ("+extensoes_permitidas[i]+" == "+extensao+") ");
            if (extensoes_permitidas[i] == extensao) 
            {
              permitida = true;
              break;
            }
          }
      }

      if (!permitida)
      {
        var ext_perm = "";
        for (a in extensoes_permitidas)
        {
          ext_perm += ext_perm == "" ? extensoes_permitidas[a] : " , " + extensoes_permitidas[a];
        }

        alert("Somente permitido envio de imagens com as seguintes extensoes: "+ext_perm);
        return false;
      }

      return true;
      }

this form is in two different views and works only in the first.

nova_pergunta.php //form to create new question

<?php echo form_open_multipart(current_url(), 'class="form-horizontal" onsubmit="return verifica_extensao()"'); ?>
        <div class="control-group">
          <label class="control-label">Área</label>
          <div class="controls">
            <select name="i_area" class="input-large">
            <option value="" selected="selected" disabled="disabled">Selecione uma Área</option>
            <?php 
                $query = $this->db->get('areas')->result_array();
                foreach ($query as $data) :
            ?>
                <option value="<?php echo $data['i_area']; ?>"><?php echo $data['nome']; ?></option>
            <?php 
                endforeach;
            ?>
            </select>
          </div>
        </div>
        <div class="control-group">
          <label class="control-label">Título</label>
          <div class="controls">
            <?php echo form_input('titulo', set_value('titulo'), 'class="input-xlarge" placeholder="Digite um Título"'); ?>
          </div>
        </div>
        <div class="control-group">
          <label class="control-label">Descrição</label>
          <div class="controls">
            <?php echo form_textarea('descricao', set_value('descricao'), 'class="input-xxlarge" rows="10" placeholder="Mensagem que será enviada e lida pelo técnico"'); ?>
          </div>
        </div>
      <div class="control-group">
          <label class="control-label">Arquivo</label>
          <div class="controls">
            <?php echo form_upload(array('name' => 'anexo_msg', 'class' => 'input_anexo')); ?>
          </div>
        </div>
        <div class="control-group">
          <div class="controls">
        <?php 
            echo validation_errors('<p class="text-error">', '</p>'); 
            if ($this->session->flashdata('msgok') != "")   echo '<p class="text-success">'.$this->session->flashdata('msgok').'</p>';
          if ($this->session->flashdata('msgerror') != "") echo $this->session->flashdata('msgerror');
        ?>
            <button type="submit" class="btn btn-primary">Enviar ao Suporte</button>
          </div>
        </div>
      <?php echo form_close(); ?>

1 answer

2

var arquivo = $(".input_anexo").val(); is only catching the first element it finds; you have to make a loop to see if the values of each element input_anexo are allowed or not; Follow an example:

var arquivos = $('.input_anexo');
var extensoes_permitidas = new Array(".jpg", ".jpeg", ".png", ".gif", ".pdf", ".php", ".js", ".swf", ".zip", ".rar", ".bmp", ".css", ".html", ".txt", ".doc", ".docx", ".word", ".7zip");
var arquivo = [],i,ext;
arquivos.each(function(ele) {
    arquivo.push($(ele).val());
});
i = arquivo.length;
for (i=0;i<=arquivo.length;i++) {
    ext = arquivo[i];
    var permitida = false;
      for (var a = 0; i < extensoes_permitidas.length; a++) {
        console.log("if ("+extensoes_permitidas[a]+" == "+ext+") ");
        if (extensoes_permitidas[a] == ext) {
          permitida = true;
          break;
        }
      }
}
  • made the change in the code plus the result is the same, now not even the first view validates.

  • @Japa I wrote a solution, you will have to adapt the code to yours - although I used part of your code the logic of it changed. It makes it easier for us to help you if you can make one Jsfiddle and link to your fiddle :)

  • http://jsfiddle.net/279fztoz/

  • @Japa arranges this fiddle to not have PHP, PHP does not work in fiddle. Go to your site, "view html source" and paste in fiddle the html you need

Browser other questions tagged

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