Skip to content Skip to sidebar Skip to footer

Js->form Validation On Inputs. Using For Loop To Get All The Inputs Index

I have a form with 4 inputs and I want to show an alert on submit. What I have done is that I have already created the warnings that goes under every input with display:none; in CS

Solution 1:

I suggest a few modifications to your validare() function:

Add a flag indicating whether the whole form is valid, assume it's true until you find an input that is invalid. Return the value of this flag.

var isValid = true;

Capture your validation messages too so you can access them by index like your inputs:

messages = document.getElementsByClassName(' alert alert-danger custom');

When you find an invalid input, display the associated message and update the valid flag to false.

if (currentInputValue == null || currentInputValue === "") {
    messages[index].style.display = "block";
    isValid = false;
}

Here is the updated function:

functionvalidare() {

    var inputs, messages, index;
    var isValid = true;

    inputs = document.getElementsByTagName('input');
    messages = document.getElementsByClassName(' alert alert-danger custom');

    for (index = 0; index < inputs.length; ++index) {
        var currentInputValue = inputs[index].value;
        if (currentInputValue == null || currentInputValue === "") {
            messages[index].style.display = "block";
            isValid = false;
        }
    }

    return isValid;
}

Updated jsbin here

Solution 2:

Here is an updated solution: jsbin

You used querySelector which return only the first element it finds with the same class, you should have used querySelectorAll which return all the selectors.

Post a Comment for "Js->form Validation On Inputs. Using For Loop To Get All The Inputs Index"