f t i +

Abstracted JavaScript Form Validator

Stephen Yager

There are many JavaScript form validators available on the market, but we've only been able to locate validators that require you to hard code the names of the form or form elements.

We've created one that can be extracted out for usage in any form.

function validateForm(f) {
var allgood = false;

To begin, we...

Create the function and giving it a name. We will pass in the form object as a parameter and assign it to the variable f. We also need to setup a variable called allgood and set this to false. We will set and check as we go along.

for (i = 0; i


We need to loop through all of the elements in the form. We do this with a standard for loop using i as the counter. We set this to 0 because arrays always start with a 0 index. Next we need to know how many times to loop so we use f.length because that is how many form elements there are. Lastly we need to increment i (it could have also been written as i = i + 1 or i += 1 but i++ looks better).

var e = f[i];
if ( e.id.toLowerCase() == 'req' ) {


We setup a new variable called e and set it to f[i]. This will be the current form element that we want to check. What we really want to check is the id of the element. We want to see if it is required and to do this we use e.id.toLowerCase(). This will return a lowercase string containing the id of the current form element. If it is equal to req then proceed. If not, just skip it and continue checking the other elements.

if ( e.type == 'checkbox' || e.type == 'radio') {
c = eval('f.elements["' + e.name + '"]');

After that...

We want to see if the element is a checkbox or a radio button. We check this with e.type (remember that e is set to the current form element). We then set c to eval('f.elements["' + e.name + '"]'). We use eval because it will take e.name (or the name of the required checkbox or radio group) and add it to the f.elements array so we can target only those elements.

for ( var j = 0; j if ( c[j].checked == true ) { allgood = true; }
} // end for loop

Now, let's...

Start to loop through all of the checkboxes or radio groups with this new loop. We need a new variable to increment so we use j (remember that i is being used for the first loop for all of the form elements). We set this one up in the same way as the first loop, but instead of using f.length we are now going to use c.length (or the number of checkboxes / radio buttons in the group). Each one of the checkboxes or radio buttons can have one of two states, true or false. So we check this state, if checked is true, we set allgood to true. We do this so we know that at least one in the group was checked. Then we close the second for loop.

if ( allgood != true ) {
alert('You did not fill out the required checkboxes / radio buttons.'); return false; }
allgood = false;
} // fi checkbox

Time to check...

See if at least one of the elements was checked. We do this by checking the variable allgood. If allgood is not true, meaning that none of the elements was checked, we inform the visitor with an alert box telling them as much, and return false so the form does not get submitted until they correct the issue. The message could be anything that you want, but we decided to keep it simple. Then close the if statement for the checkboxes.

else if ( e.value.trim().length e.value = e.value.trim();
alert('You did not put in enough text in the required boxes');
return false;
} // fi value.trim()
} // fi req
} // end for loop
return true;
} // end function

Last, but not least...

Check the text input boxes. We do this with the else if statement. We want to make sure it is not just null, but has at least 5 characters. If it is shorter than 5 characters with the whitespace removed we tell the visitor and fix the appropriate text field for them. Then we close the statement for the required if statement and the first for loop. If we have made it this far in the function without getting stopped, then all the required fields were filled out correctly, so we return true and close the function.

One thing that was used in the function above was the trim prototype. Add this anywhere in the code to give you the same functionality as PHP's trim() function:

String.prototype.trim = function() {
	return this.replace(/^s+|s+$/g,"");

Time to implement!

Now that we have the validateForm function how do we implement it? Like this:

<form action="#" method="post">First Name: <br>Last Name: <br><label> Red</label><br><label> Blue</label></form>

And there you have it! 

A form validator that has been abstracted and will check all your forms without the need for hard coding in any form names or form elements. success-driven-websites-icon

Is a Growth Driven Design strategy the right approach for your next web redesign? Learn more in the A Web-Dev's Guide to Growth Driven Design ebook.
Definitely not spam

Sign up for our newsletter

Don't worry - we only average, like, two emojis per subject line.

Got a question for Stephen Yager?

Message the author of this post and they'll get back to you.

Fire Away