how to validate form using single function in javascript

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

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
Moderator
1170 Points
210 Posts
Marked as answer      

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
banner

Blog

Active User (0)

No Active User!
 Log In to Chat