Validation of forms with javascript

Asked

Viewed 2,032 times

7

I’m having trouble validating a form with pure javascript, when it arrives in the field of the type "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');
}

Example in Jsbin

4 answers

3

tipo == 'checkbox' && document.form.nome.checked !== true

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

tipo == 'checkbox' && inputs[i].checked !== true
  • 1

    Exactly. It worked here.

  • @That’s what you lost, but I always have to select the two checkboxes, otherwise there will always be an error, only there will be a checkbox that the user will leave empty. That’s why I tried to verify the name... Is there any solution to this?

  • Remove the return false and use a boolean variable to control whether the form was validated at the end before sending. To do so false in each failed validation. I included a reply my below with the full edited source of the function.

3


Update

Based on the discussed so far, follows functional final version: http://jsbin.com/ruhocoru/16

<!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’s a little bug in the relationship of inputs[radio] because there is no label for each of them. This is in your charge to resolve :)

  • Thanks @Thiago, it worked here, but generates a kind of loop whenever I use two inputs type radio, whenever I select 1 gives error in the other and vice versa, you know how to solve this, sorry man, is that I’m beginner in javascript rs

  • 1

    I will analyze and put a correction :)

  • 1

    Man, it’s hard to get out here, but relax I put something as soon as I progress...

  • Put, thanks so much for the strength @Thiago! : ) I’ve been trying it since 4:00 pm Oo hahaha

  • I can change the font structure and the way to show the errors, or it has to be obeying its original source?

  • You can feel free to change the structure @Thiago, :D just the way to demonstrate the error that would have to be something similar...

  • 1

    It was hard work, but I managed to get out the other side. Take a look at jsbin...

  • 1

    Thanks a lot @Thiago, it worked perfectly, that’s right :)

  • Glad to have helped! Success!

Show 4 more comments

2

Here is an example using AJAX. This example is of student registration

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

});
  • Thanks @Flávia, but for this application I can only use pure javascript, I can’t use Jquery.

1

It is possible to perform such validation with HTML5.

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

Browser other questions tagged

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