Validating forms with javascript

7

I'm having problems validating a form with pure javascript , when it arrives in the type field "checkbox" always returns false, even with "checked = true" .

Why is this happening? How can I resolve?

function val(){
    var inputs = document.form.getElementsByTagName('input');
    var label = document.form.getElementsByTagName('label');

    for(i=0;i<inputs.length;i++){

        var tipo = inputs[i].type;
        var nome = inputs[i].getAttribute('name');
        var elemento = inputs[i].getAttribute('id');

        if(tipo == 'text' && inputs[i].value.length < 5){

            label[i].childNodes.item(1).innerHTML = '*';
            document.getElementById(elemento).focus();
            return false;

        }else if(tipo == 'checkbox' && document.form.nome.checked !== true){

            label[i].childNodes.item(1).innerHTML = '*';
            document.getElementById(elemento).focus();
            return false;

        }else if(tipo == 'radio' &&  document.form.nome.checked !== true){

            label[i].childNodes.item(1).innerHTML = '*';
            document.getElementById(elemento).focus();
            return false;

        }else{
            label[i].childNodes.item(1).innerHTML = '';
            }
    }
    alert('enviado');
}

JSBin Example

    
asked by anonymous 20.02.2014 / 23:45

4 answers

3

Update

Based on the discussed so far, follow functional final version: link

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>
  function val(){
    var validado = true;
    var inputs = document.form.getElementsByTagName('input');
    var labels = document.form.getElementsByTagName('label');


    for (i = 0; i < inputs.length; i++) {
      var elem = inputs[i];
      var tipo = elem.type;

      labels[i].innerHTML = labels[i].innerHTML.replace(/[*]/g, "");

      if (tipo == 'text' && elem.value.length < 5) {
        if (labels[i].innerHTML.indexOf("*") < 0) labels[i].innerHTML += '*';
        validado = false;
      } else if (tipo == 'checkbox' && elem.checked !== true) {
        if (labels[i].innerHTML.indexOf("*") < 0) labels[i].innerHTML += '*';
        validado = false;
      } else if (tipo == 'radio' &&  elem.checked !== true) {
        var radioElems = document.getElementsByName(elem.name);
        var radioValidated = false;

        for (j = 0; j < radioElems.length; j++) {
           if (radioElems[j].checked)
             radioValidated = true;
        }

        if (!radioValidated) {
          labels[i].innerHTML += '*';
          validado = false;
        }
      }
    }

    if (validado)
      alert('enviado');
  }
</script>
</head>

<body>
  <form name="form" action="#">
    <label for="nome">Seu nome</label>
    <input type="text" name="nome" value="Tiago" /><br/><br/>

    <label for="check1">Pergunta 1</label><br />
    <input type="checkbox" name="check1" checked="checked" />Opção 1<br/><br/>

    <label for="check2">Pergunta 2</label><br />
    <input type="checkbox" name="check2" checked="checked" />Opção 2<br/><br/>

    <label for="rd">Selecione uma opção</label><br />
    <input type="radio" name="rd" />Sim
    <input type="radio" name="rd" />Não
  </form>

  <div id="message" style="margin: 20px 0;"></div>
  <button type="button" onclick="return val();">valida</button>
</body>
</html>

There is a small bug in the inputs[radio] relationship because there is no label for each of them. This one is in charge to resolve:)

    
21.02.2014 / 01:08
3
tipo == 'checkbox' && document.form.nome.checked !== true

I believe that instead of document.form.nome would be, the variable input to be compared, since nome is of type text

tipo == 'checkbox' && inputs[i].checked !== true
    
20.02.2014 / 23:50
2

Follow an example using AJAX. This example is for student enrollment.

$(document).ready(function(){
    $("#formCad").submit(function(event) {                          
        event.preventDefault(); //tira o evento do submit

        var curso = new Array();
                        $("input[name='curso[]']:checked").each(function() {
                            curso.push($(this).val());
                        });
        $.post(
            "cadastro_usuario.php",
            { nome:  curso: curso },
            function(data){ 
                $('#retornoAjax').hide();
                $('#retornoAjax').css('color','blue');                  
                $('#retornoAjax').html(data);   
                $('#retornoAjax').fadeIn(1000);     
            }
        );     
    });

});
    
21.02.2014 / 00:50
1

You can perform such validation with HTML5.

<input type="checkbox" id="model_confirmar" name="model[confirmar]" required />
    
21.02.2014 / 15:06