Validate fields within separate Ivs in a single form

Asked

Viewed 95 times

0

Within a single form I have 3 divs, that change as the user clicks on próximo. But for the user to be able to click próximo the mandatory fields of div which is currently being shown must be filled.

To validate the form has a code as follows:

var form_validation = function() {
    var e = function() {
            jQuery(".form-valide").validate({
                ignore: [],
                errorClass: "invalid-feedback animated fadeInDown",
                errorElement: "div",
                errorPlacement: function(e, a) {
                    jQuery(a).parents(".form-group > div").append(e)
                },
                highlight: function(e) {
                    jQuery(e).closest(".form-group").removeClass("is-invalid").addClass("is-invalid")
                },
                success: function(e) {
                    jQuery(e).closest(".form-group").removeClass("is-invalid"), jQuery(e).remove()
                },
                rules: {
                  "nome_campo":{
                       required: !0
                   }
                },
                messages:{
                    "nome_campo":{
                         required: "mensagem a ser mostrada quando não preenchido"
                     }
                }
            })
    }
    return {
        init: function() {
            e(), a(), jQuery(".js-select2").on("change", function() {
                jQuery(this).valid()
            })
        }
    }
}();
jQuery(function() {
    form_validation.init()
});

This way I can specify the field that is required and the error message to be shown. But as far as I’ve researched I can only do this to tag form, but not to div.

I was wondering if there’s any way to do something similar for the divs and only allow to pass to the next div when all mandatory fields are completed and so on until you reach the div that allows you to click on salvar. But if the user clicks próximo and the required fields are not populated showing the error messages.

  • I could try to help if I could reproduce the code, and for that I would need the form HTML.

  • I will try to put here, the complicated code that is the company I do internship, there is not to show much. I will change some things in it and already put. Vlwzaço!

2 answers

1


If I understand correctly, it is possible that you validate the fields before showing the next div

The bottom I made an example, so you can get an idea, you can run to see the behavior.

function goToDiv2(){
  const nome = document.getElementById('nome').value;
  const validator = nome.length > 0;
  nextDiv('div-1','div-2',validator,'error-message-1')
}

function goToDiv3(){
  const idade = document.getElementById('idade').value;
  const validator = idade >= 18;
  nextDiv('div-2','div-3',validator,'error-message-2')
}

function submitData(){
  const fone = document.getElementById('telefone').value;
  const validator = fone.trim().length > 10
  nextDiv('div-3',null,validator,'error-message-3')
  if(validator){
    alert('tudo certo')
  }
}

function nextDiv(currentDivId, nextDivId, validator, elementErroId){
  const div = document.getElementById(currentDivId)
  const nextDiv = document.getElementById(nextDivId)
  if(!validator){
    const small = document.getElementById(elementErroId)
    small.innerHTML = div.dataset.erro_msg
    return;
  }
  div.classList.toggle('hide')
  if(nextDiv){
    nextDiv.classList.toggle('hide')  
  }
}
.hide{
  display: none;
}

small{
  color : red;  
}
<div id="div-1" data-erro_msg="o nome não pode ser vazio"> 
  <label for="nome">Nome: </label>
  <input id="nome" placeholder="insira seu nome"/> 
  <button onclick="goToDiv2()"> next </button>
  <small id="error-message-1"> </small> 
</div>
<div class="hide" id="div-2" data-erro_msg="você precisa ser maior de idade"> 
  <label for="idade">Idade: </label>
  <input type="number" id="idade" placeholder="insira sua idade"/> 
  <button onclick="goToDiv3()"> next </button>
  <small id="error-message-2"> </small> 
</div>
<div class="hide" id="div-3" data-erro_msg="insira o telefone com o DDD"> 
  <label for="telefone">Telefone: </label>
  <input id="telefone" placeholder="insira seu telefone"/> 
  <button onclick="submitData()"> next </button>
  <small id="error-message-3"> </small> 
</div>

0

The answer was the perfect basis for what I needed.

I just made a few adaptations and I’ll leave it here in case someone needs it too.

//Essa aqui é chamada no .ready pra esconder as labels dos erros antes de mostrar

function hideErrorDiv1() { //Idem pra div2
    const elementErroId = ["erro-id1", "erro-id2", "erro-id3"];

    hideElements(elementErroId);
}

function hideElements( elementErroId ) {

        for (let index = 0; index < elementErroId.length; index++) {
            const field = elementErroId[index];
            const element = document.getElementById(field);
            $(element).hide();   
        }
}

goToDiv2() {
    const elementId = ["id1", "id2", "id3"];

    const elementErroId = ["erro-id1", "erro-id2", "erro-id3"];

    goToNextDiv("div1", "div2", elementErroId, elementId);
}

goToDiv3() {
    const elementId = ["id4", "id5", "id6"];

    const elementErroId = ["erro-id4", "erro-id5", "erro-id6"];

    goToNextDiv("div2", "div3", elementErroId, elementId);
}

function goToNextDiv( currentDivId, nextDivId, elementErroId, elementId ) {
    const div = document.getElementById(currentDivId);
    const nextDiv = document.getElementById(nextDivId);
    var canGoNext = true;

    for (let index = 0; index < elementId.length; index++) {
        const field = document.getElementById(elementId[index]);
        const errorLabel = document.getElementById(elementErroId[index]);

        if($(field).val() == null || $(field).val() == 0) {
            canGoNext = canGoNext && false;
            $(errorLabel).show();
        } 
        else {
            canGoNext = canGoNext && true;
            $(errorLabel).hide();
        }

    }

    if(canGoNext) {

        $(div).hide();
        $(nextDiv).show();
    }
}

Html:

<form>
    <div id="div1">

        <div>
            <label>Nome Campo</label>
            <input type="text" id="id1">
            <label id="erro-id1">Preenchimento Obrigatório</label>
        </div>

        <div>
            <label>Nome Campo</label>
            <input type="text" id="id2">
            <label id="erro-id2">Preenchimento Obrigatório</label>
        </div>

        <div>
            <label>Nome Campo</label>
            <input type="text" id="id3">
            <label id="erro-id3">Preenchimento Obrigatório</label>
        </div>

        <div>
            <button type="button" onclick="goToDiv2()"> Próximo </button>
        </div>

    </div>

    <div id="div2">
        <!--similar div1-->
    </div>

</form>

Browser other questions tagged

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