Universal Form Validation - Good Form, Jack!
(Page 3 of 5 )
I’m absolutely certain that the most pressing thought racing through your mind this very moment is ‘how on Earth could we accomplish such a great feat by the use of only one function?’ Ok, more likely is that the real pressing thought you have is wondering whether or not to eat that leftover pizza for breakfast.
Regardless of that, I’m going to answer both questions. Yes, eat the pizza. Who knows what kind of valuable bacteria may have multiplied overnight. As for the forms, all we need to do is find some way of handling all possible circumstances that may exist and check for validity of the required fields. If we can determine the entries for each to be sufficient, then we can submit the form. Otherwise, we barf out one of those bothersome messages making the user fully aware of their deficiencies. Let’s walk through the code.
function checkForm
( f ) {
var strMessage = 'Please fix the following:nn';
var objTemp;
var strName = ''
var boolIsValid = true;
for ( var i = 0;
i < f.elements.length;
i++ ) {
So, we’ve specified ‘f’ as the form we’re going to check, and to do that we’ll iterate though each field, or element, within the form. We’ve set the initial error message, and the Boolean flag to throw up if an element is invalid.
objTemp
= f.elements[i];
strName = objTemp.name
if ( strName.substr(
strName.length - 9 ) ==
'_required' ) {
So you can see that we’re only going to work with required elements. We don’t care about anything else, quite frankly!
//strName =
// strName.replace( /data_/, '' );
strName = strName.replace( /_required/, '' );
strName = strName.replace( /_/g, ' ' );
strName = strName.toLowerCase();
We’ve accomplished a number of things here. If you’re concerned with the first, commented-out line, you’ll have to read right through to the conclusion the chilling answer to that mystery. The next removes three lines prepare the name for the error message, by removing the ‘_required’ suffix, but spacing out the words, and by making it all a nice, readable lower case.
if
( objTemp.value == '' ) {
boolIsValid = false;
strMessage += strName + ' is emptyn';
} else if ( objTemp.type == 'radio' ) {
boolIsValid = false;
for ( var j = 0; j < objTemp.length; j++ ) {
if ( objTemp[j].checked ) {
boolIsValid = true;
break;
}
}
}
This is the first round of checking. First off we can simply look for an entry other than ‘’. That simply doesn’t work for radio buttons however, so we are forced to search through them all to find at least one that is checked. Next we can move on to more specific targets.
if
(strName.indexOf('first name') != -1
&& objTemp.value == 'First' ) {
boolIsValid = false;
strMessage += strName +
' is invalidn';
} else if (strName.indexOf('last name') != -1
&& objTemp.value == 'Last' ) {
boolIsValid = false;
strMessage += strName + ' is invalidn';
Here I have added in a little code just to check that the default values have not been left in the first and last name field. I often place the ‘First” and ‘Last’ right in the fields as a tool tip, and have it disappear when focused on the field. This will ensure they’ve at least entered some name, even if it is Richard Simmons, or my favorite, Jim Bob.
} else if
(strName.indexOf('email') != -1 &&
(objTemp.value.indexOf(<A href="mailto:'@'">'@'</A>) == -1
|| objTemp.value.indexOf('.')== -1))
{
boolIsValid = false;
strMessage += strName + ' is invalidn';
This is an over-simplified email checking, checking only for an ‘@’ and a ‘.’. I highly recommend using a regular expression for this, but I don’t want to step on Melonfire’s toes. You can use his, found at
http://www.devshed.com/c/a/JavaScript/Form-Validation-with-JavaScript/7/.
} else if
(strName == 'verify password' &&
(objTemp.value
!= f.data_password_required.value)){
boolIsValid = false;
strMessage += 'Passwords do not match!n';
}
}
}
This was something I threw in once for an application where new users were signing up. This would make sure they typed the same password twice. I didn’t totally need to include this in the article, but I left it in to demonstrate just how flexible the function is. You can really add in any routine to check any circumstance you come up against, and so long as you have the ‘_required’ attached to the new fields.
if ( boolIsValid == true ) {
return true;
} else {
alert( strMessage );
return false;
}
}
This is the last little piece of the pie. We here check if our Boolean flag has been tripped, and raise the alarm if it has. Now, you could get fancy and re-focus the user on the first missing element, but once again that’s entirely up to your creative customization skills.
If data has been entered, then the form is off to the cleaners. However, what happens when you see entries in your database with a phone number of 1-800-YOU-WISH, or an age of ‘asdf’? These are supposed to be numbers! NUMBERS! And our amazing universal form checker let them through just because they were more than nothing! How can we handle such situations? Perhaps we could continue to modify the form checker to check for numeric values for fields name ‘phone’ and ‘age’, but we’d spend the rest of our waking lives adding ‘year’ and ‘day’ and every other numeric field to the list. There’s got to be a better way! Oh yes, read on…
Next: Pick a Number, Any Number! >>
More JavaScript Articles
More By Justin Cook