Validation configuration in dynamic fields

10

I have a problem that is as follows, I have the fields: Name, Age and Text;

In a part of the system I register that the Text field will only appear if the Name field is equal to PH and the Age field has the value 20 with both true conditions and then I release the Text field. / p>

My difficulty in this part is because it can have many fields because the form is set up by the client, ie the client can register 20, 30 fields for this form and all have a specific rule to release some other field. Is there a plugin that checks or does this type of validation?

At this point I tried the following, but it only validated this way if it was 1 to 1. But in this case it can be N-1 or 1-N or would it be better to create an intermediate table for this action?

$(function () {
    var campoDependente = '#codigo_<?php echo $condicao->atividade_campo_dependente ?>',
            campoTrigger = '#codigo_<?php echo $condicao->atividade_campo ?>',
            valor = '<?php echo trim($condicao->condicao) ?>';


    function mostrar() {

        var val = '';
        var checkbox = $(campoTrigger + ' input:checked');
        var select = $(campoTrigger + ' select > option:selected');
        var input = $(campoTrigger + ' input');

        if (checkbox.length > 0) {
            val = $.trim(checkbox.parent().text());

        } else if (select.length > 0) {
            val = $.trim(select.text());

        } else {
            val = input.val();

        }

        if (val == valor) {
            $(campoDependente).css('display', 'inline-block');
        } else {
            $(campoDependente).css('display', 'none');
        }

    }

    mostrar();
    $(campoTrigger).change(mostrar);

});
    
asked by anonymous 21.05.2015 / 20:36

1 answer

6

You have to create a logic of checks. You can do this on an object with verification rules. Each key could be the name or id of the input that will appear if some rules are checked. In this way there will be a structure that easily mounts with JS.

Example idea:

var regras = {
    texto: {
        nome: 'PH',
        idade: 20
    }
};

and then a code that would look for DOM rules and elements to check everything:

var inputs = document.querySelectorAll('input');
for (var i = 0; i < inputs.length; i++) {
    inputs[i].addEventListener('keyup', verificador);
}

function procurador(chave, objeto) {
    if (chave in objeto) return chave;
    var match = Object.keys(objeto).filter(function (key) {
        var subObjeto = objeto[key];
        if (typeof subObjeto != 'object') return false;
        return procurador(chave, subObjeto);
    })[0];
    return match;
}

function verificador() {
    var prop = this.name; // saber qual input recebeu keyup
    if (!prop) return;    // caso não tenha nome interromper
        Object.keys(regras).forEach(function (regra) { // iterar as regras
        var regrasLocais = Object.keys(regras[regra]); // regras a cumprir
        var target = document.querySelector('[name="' + regra + '"');
        var valores = regrasLocais.map(function (nome) { // mapear regras com o input respetivo guardando o seu valor
            return document.querySelector('[name="' + nome + '"').value;
        });
        var valida = valores.filter(function (value, i) { // verificar quais inputs têm o valor == ao que é esperado pela regra
            var original = regras[regra][regrasLocais[i]];
            return value == original;
        });
        if (valida.length == regrasLocais.length) target.classList.remove('invalido'); // se todas as verificações tiverem passado
        else target.classList.add('invalido'); // caso falhe a validação
    });
}

jsFiddle: link

A more complex example with functions within check rules would be: link

It took me a while to make this code. I found the question and the problem interesting then I placed it in github as well. I hope this is what you are looking for:)

    
21.05.2015 / 23:27