Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Automate Your Form Validation-3 : Page 3


advertisement
Setting Up the Support Functions
When writing validation code, I find it helpful to include generic support functions that provide much of the grunt work. Since the purpose of the generic functions is to make them re-usable, include them in a separate file and reference them in your HTML page like this:

<script type="text/javascript" src="validationFunctions.js"></script>

Then, add the following functions to the script file:

// Support Functions function strip(filter,str){ var i,curChar; var retStr = ''; var len = str.length; for(i=0; i<len; i++){ curChar = str.charAt(i); if(filter.indexOf(curChar)<0) //not in filter, keep it retStr += curChar; } return retStr; } function reformat(str){ var arg; var pos = 0; var retStr = ''; var len = reformat.arguments.length; for(var i=1; i<len; i++){ arg = reformat.arguments[i]; if(i%2==1) retStr += arg; else{ retStr += str.substring(pos, pos + arg); pos += arg; } } return retStr; } //End Support Functions

Validating forms is much easier if you can eliminate extraneous characters and deal only with the significant input data. For example, when dealing with a phone number, you should be concerned with the numbers, not with the dashes and parentheses. The strip() function strips out garbage characters from strings based on the filter argument. It compares each character in the string argument with those in the filter. If the character in the string matches any of the characters in the filter, the character is discarded. If no match is made, the character is kept. The reformat() function lets you apply formatting rules to strings as needed. In essence, the function takes a string as the first argument and then a series of arguments in groups of three. In each group of three arguments, you must include a set of preceding characters, the number of characters to skip, and a set of following characters. The code wraps the formatting characters around the significant parts of the data.

For example, to wrap parentheses around the characters in a three-character string, you would write:



stringValue = reformat(stringValue,"(",3,")");

The key lies in knowing how many characters should be in the string you're formatting.


Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date