Home arrow JavaScript arrow Page 3 - Universal Form Validation
JAVASCRIPT

Universal Form Validation


We have witnessed the wonders of JavaScript and its ability to ensure that our forms are properly filled before submission. But it gets so laborious to type and modify and update form validation scripts for every for in every application. Take heart! Upon reading and applying the methods in this article, you will never again have to worry about client-side validation! Hazzah!

Author Info:
By: Justin Cook
Rating: 4 stars4 stars4 stars4 stars4 stars / 26
February 02, 2004
TABLE OF CONTENTS:
  1. · Universal Form Validation
  2. · First, the Forms
  3. · Good Form, Jack!
  4. · Pick a Number, Any Number!
  5. · And Knowing is Half the Battle

print this article
SEARCH DEVARTICLES

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) { 
 
var strMessage 'Please fix the following:nn';
 
var objTemp
 
var strName ''
 
var boolIsValid true;
 
for ( var 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 ) == 
     
'_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 0objTemp.lengthj++ ) {
  
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') != -
     
&& objTemp.value == 'First' ) {
 boolIsValid 
false;
 strMessage 
+= strName 
 
' is invalidn';
} else if (strName.indexOf('last name') != -
  
&& 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') != -&& 
 
(objTemp.value.indexOf(<A href="mailto:'@'">'@'</A>) == -
 
|| 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…


blog comments powered by Disqus
JAVASCRIPT ARTICLES

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials