how to validate form using single function in javascript

Jak
Jak
Member
858 Points
132 Posts
how to validate form using single function in javascript
Views: 9337
Total Answered: 1
Total Marked As Answer: 1
Posted On: 21-Sep-2014 23:41

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
Teacher
4822 Points
23 Posts
         

function validateForm(form) {
    var isValid = true;

    // Loop through input elements and ensure they have a value
    var inputs = form.getElementsByTagName("input");

    // Validate input elements
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].value === undefined || inputs[i].value.length == 0) {
            // Add your validation class to it
            inputs[i].class = invalid;
            document.getElementById("lblInputMessage_" + i).innerHTML =
                "This Field is Required!";
            isValid = false;
        }
    }

    // Loop through input elements and ensure they have a value
    var textareas = form.getElementsByTagName("textarea");

    // Validate input elements
    for (var i = 0; i < inputs.length; i++) {
        if (textareas[i].value === undefined || textareas[i].value.length == 0) {
            // Add your validation class to it
            textareas[i].class = invalid;
            document.getElementById("lbltextareaMessage_" + i).innerHTML =
                "This Field is Required!";
            isValid = false;
        }
    }

    // Loop through select elements and ensure they have a value
    var selects = form.getElementsByTagName("select");

    // Validate input elements
    for (var i = 0; i < inputs.length; i++) {
        if (selects[i].selectedIndex === undefined ||
            selects[i].options[selects[i].selectedIndex].value === undefined ||
            selects[i].options[selects[i].selectedIndex].value.length == 0) {
            // Add your validation class to it
            selects[i].class = invalid;
            document.getElementById("lblSelectreaMessage_" + i).innerHTML =
                "This Field is Required!";
            isValid = false;
        }
    }

    // Display a message indicating the form was invalid
    if (!isValid) {
        alert("The form is invalid, please fix the highlighted elements");
        return false;
    }

    return isValid;
}

Posted On: 21-Sep-2014 23:50
 Log In to Chat