JavaScript validation using inputs as array
<p>Hi I am trying to validate my inputs using JavaScript, I have the inputs in an array and I am trying to use them to extract information like <code>.value</code> and set values such as <code>.className</code>. This is not working as I would like it to. What I want the code to do is if I define <code>input[1] = document.forms["register"]["username"];</code> then use <code>input[1].value</code> it interprets this as if I have written <code>document.forms["register"]["username"].value</code></p>

<p>Here is my original code:</p>

<pre><code>function validateForm() {
    var inputs = [];
    inputs[0] = document.forms["register"]["firstname"];
    inputs[1] = document.forms["register"]["lastname"];
    inputs[2] = document.forms["register"]["username"];
    inputs[3] = document.forms["register"]["email"];
    inputs[4] = document.forms["register"]["password"];
    inputs[5] = document.forms["register"]["confirmpassword"];

    for (i = 0; i &lt; inputs.length; i++) {
        if (inputs[i].value == null || inputs[i].value == "") {
            alert("Highlighted fields must be filled out");
            inputs[i].className += " invalid";
            return false;

        }
    }

    return true;
}
</code></pre>

<p>Here is my updated code, I am unsure of whether this is good practice: </p>

<pre><code>        function validateForm() {
        var error = false;
        var inputs = [];
            inputs[0] = document.forms["register"]["firstname"];
            inputs[1] = document.forms["register"]["lastname"];
            inputs[2] = document.forms["register"]["username"];
            inputs[3] = document.forms["register"]["email"];
            inputs[4] = document.forms["register"]["password"];
            inputs[5] = document.forms["register"]["confirmpassword"];
            console.log(inputs.length);

        for (i = 0; i &lt; (inputs.length); i++) { 
            if (inputs[i].value == null || inputs[i].value == "") {
                error = true;
                inputs[i].className += " invalid";
                if (inputs[i] == (inputs.length - 1)) {
                    alert("Highlighted fields must be filled out");
                    return false;

                }
            }
        }

    if (error == false) {
        return true;
    }

    alert("Highlighted fields must be filled out");
    return false;
    }
</code></pre>

<p>The class invalid adds a red border to the field.</p>

<p>Thanks.</p>