Validation configuration in dynamic fields

Asked

Viewed 383 times

10

I have a problem which is this, 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 have the value 20 with the two true conditions I then release the Text field.

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

At that moment I tried the following, but only validate this way if it was 1 to 1. But in this case it can be N-1 or 1-N or it would be better to create an intermediate table for such an 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);

});

1 answer

6


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

Example of the idea:

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

and then a code that would look for rules and DOM elements to and 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: http://jsfiddle.net/vazuLkf0/1/

A more complex example with functions within verification rules would be: http://jsfiddle.net/vazuLkf0/5/

It took me a while to make this code. I found the question and the problem interesting then put on github also.
I hope this is what you’re looking for :)

  • 1

    Just one more thing I didn’t mention and when the fields aren’t just input’s I tried to put here in variable values in the checker function I tried to group the selectors but unsuccessfully for example I have fields that are selected in this precise case from . text and not from . value as you would in that case ? kind of take the text of the fields universally and got good the good initiative code to put it on github

  • @Paulohenrique and in this case the option have value? if they have no value select.value returns the text/.innerHTML

  • in this case the options have value yes, example: sim has value 27 the numbers in the values are represented the ID in the database, if the client selects one of them I have to save in the bank and then bring marked the respective value and the .innerHTML for some reason behind the input as empty even filled.

Browser other questions tagged

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