Estoy tratando de crear un formulario de varios pasos con validación basada en campos obligatorios. El Javascript actual que estoy usando solo busca campos que se completan para validar el formulario. Pero, ¿cómo hago para que ignore los campos que no están marcados como "requeridos" en el html?
¡Gracias!
function validateForm() { // This function deals with validation of the form fields var x, y, i, valid = true; x = document.getElementsByClassName("tab"); y = x[currentTab].getElementsByTagName("input"); // A loop that checks every input field in the current tab: for (i = 0; i < y.length; i++) { // If a field is empty... if (y[i].value == "") { // add an "invalid" class to the field: y[i].className += " invalid"; // and set the current valid status to false: valid = false; } } // If the valid status is true, mark the step as finished and valid: if (valid) { document.getElementsByClassName("step")[currentTab].className += " finish"; } return valid; // return the valid status }Pero, ¿cómo hago para que ignore los campos que no están marcados como "requeridos" en el html?
La siguiente solución verifica la propiedad required en los elementos de input . Entonces, en el bucle for , lo primero que haría es if(!y[i].required){ continue; } , en otras palabras, si y[i].required es undefined , continue (u omita esta iteración).
function validateForm() { // This function deals with validation of the form fields var x, y, i, valid = true; x = document.getElementsByClassName("tab"); y = x[currentTab].getElementsByTagName("input"); // A loop that checks every input field in the current tab: for (i = 0; i < y.length; i++) { // --> if y[i].required is undefined... skip to the next <-- if(!y[i].required){ continue; } // If a field is empty... if (y[i].value == "") { // add an "invalid" class to the field: y[i].className += " invalid"; // and set the current valid status to false: valid = false; } } // If the valid status is true, mark the step as finished and valid: if (valid) { document.getElementsByClassName("step")[currentTab].className += " finish"; } return valid; // return the valid status }