I’m trying to make a JavaScript function that can validate a form. I keep thinking that the use of getElementByTagName(form) would work as a way to extract all inputs and in turn, cycle through them for proper validation sequences. Unfortunately, I’m lousy at JavaScript and for some reason, what I have so far isn’t even coming close to working.

Take the following as an example…

function validate(form){
   var inputs = form.getElementByTagName('input');

I can’t seem to understand why “inputs” is undefined. I thought I was taking the form and throwing into the “validate” function where the “form.getElementByTagName” would have access to the subsequent elements indicated in the argument being passed (input) but apparently, I was way off.

Can someone help me out here?

“inputs” would be a nodelist, not a boolean.

You’ll have to take a look at each node and take a look at the field’s value.

If you search for javascript form validation, you’ll come up with all sorts of examples (some of which are better than others).

It’s getElementsByTagName - plural. :wink:

You’ll need to either select a specific one from the collection returned, or loop through them:

var inputs = form.getElementByTagName('input');
var fourthinput = inputs[3];
for (var i = 0, j = inputs.length; i < j; i++) {

The standard for when working with forms is to use the elements object within the form itself, to gain access to the submittable parts.

Here’s a post I made yesterday about accessing form elements that takes you through the different details, and the motivations for them.

The part near the end should be updated though so that it reads:

function validateForm() {
    var form = this,
        username = form.elements.username,
        password = form.elements.password;

Thanks for the great input and resources. I hope you can help me out with one more question…

Could someone explain to me what exactly form is within “function_name(form)”? Form is an argument, right? For some reason, I keep wanting to think that it behaves differently than your “normal” or traditional arguments due to the nature of which JavaScript plays with things…

Any clarification on this is appreciated. Oh, and I’m having some issues accessing some of the links you guys posted. I’m not sure if it’s me or the connection but I’ll try to look at those again later.

Yes, form is just an argument, and in the case of the validate function, the form argument would be a reference to the form element on the page.
That requires explicitly specifying the form from javascript.

Here’s an example:

var el = document.getElementById('someForm');
el.onsubmit = processSubmit();

function processSubmit() {
    var form = this;
    return validate(form);

The this keyword refers to the element that fired the onsubmit event.