Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate between each input to validate value

I have this code which validate the input's value if empty and shows the message error with a twitter bootstrap popover:

$(document).on("ready", login_events());

function login_events(){

    $("#userId, #password").on("change", validateEmpty);
    $("#loginButton").on("click", validateAll);

}

function validateEmpty(){

    input = $(this);
    input.popover({animation: true, placement: 'right', trigger: 'manual', title: 'Field is Empty', content: input.attr("data-empty-message")});
    isValid = true;

    if(input.val() === ""){
        input.popover('show');
        isValid =  false;
    }
    else{
        input.popover('hide');
    }

    return isValid;

}

This works perfectly when the change event is done but I want to do another function which will iterate between each input in the form, validate if it's empty (validateEmpty()) and preventDefault if any are empty.

As you can see I have the click event setup for the #loginButton to run the validateAll function which I have something like this but cannot figure out a right way to do it:

function validateAll(event){

    $("#loginForm input").each(validateEmpty);

}
like image 867
Gabriel Ramirez Martinez Avatar asked Nov 12 '22 17:11

Gabriel Ramirez Martinez


1 Answers

Try this closure:

function validateAll(event){
    var isValid = true;
    $("#loginForm input").each(function (){
        input = $(this);
        input.popover({animation: true, placement: 'right', trigger: 'manual', title: 'Field is Empty', content: input.attr("data-empty-message")});
        isValid = true;

        if(input.val() === ""){
            input.popover('show');
            if (isValid)
                isValid = false;
        }
    });
    if (!isValid) {
        alert('form is not valid!');
    }
}
like image 88
VMAtm Avatar answered Nov 15 '22 10:11

VMAtm