How to only validate fields that are visible?

2

I have a form with several fields (inputs, selects), but some are as display: block and others as display:none; as I put validation in all when I submit the form I wanted to check only those that are visible on the screen and not all.

    
asked by anonymous 04.05.2015 / 13:38

1 answer

1

Option 1 - pure Javascript

I have created the following function, which takes into account display: none and visibility: hidden :

function estaVisivel(elm){
    var estaVisivel = (elm.offsetWidth > 0 && elm.offsetHeight > 0) && // display: none
    window.getComputedStyle(elm,null).getPropertyValue("visibility") != "hidden"; 

    return estaVisivel;    
}

Some Tests:

var form = document.getElementById("form");
for (var i = 0; i < form.elements.length; i++) {
    var elm = form.elements[i];
    var visible = estaVisivel(elm);
    log("<br />Elemento: " + elm.id + " visible = " + visible);
}

 function estaVisivel(elm){
        var estaVisivel = (elm.offsetWidth > 0 && elm.offsetHeight > 0) && // display: none
        window.getComputedStyle(elm,null).getPropertyValue("visibility") != "hidden"; 
 
        return estaVisivel;    
    }

function log(text){
    document.getElementById("resultado").innerHTML += text;
}
.hidden {
    visibility: hidden;
}

.display-none {
    display: none;
}
<form id="form">      
    <input id="b" type="text" class="hidden" /><br />
    <select id="c" class="hidden"><option>1</option></select><br />
    <textarea id="d" class="hidden"></textarea><br />
       
    <input id="b1" type="text" class="display-none" /><br />
    <select id="c1" class="display-none"><option>1</option></select><br />
    <textarea id="d1" class="display-none"></textarea><br />
        
    <input id="b2" type="text" /><br />
    <select id="c2"><option>1</option></select><br />
    <textarea id="d2"></textarea><br />
</form>

<div id="resultado"></div>

Option 2 - jQuery

Simply use the :visible pseudo selector:

if($("#elemento").is(":visible"))
    // validação
    
04.05.2015 / 16:15