APIFinder
   The essential directory of application programming interfaces
Submit an API
DevX
Function
Language/OS
Contribute
About
Browse DevX
advertisement
Log In | Register
JavaScript Form Validation, the Aspect-Oriented Way
Did you know you can apply Aspect-Oriented Programming to client-side JavaScript form validation? Read on to find out how. 
February 5, 2008

advertisement
By now you likely have worked with, or at least experimented with, cross-cutting concerns, a core element of Aspect-Oriented Programming (AOP). AOP is an excellent and very compelling approach for traditional software development, but you may be surprised to learn that it can also be applied to client-side JavaScript form validation, thanks to Dan G. Switzer's development of the qForms JavaScript API.

This 10-Minute Solution examines the qForms JavaScript API, highlighting the ability to apply JS form validation logic to the forms of a page in an aspect-oriented way. With qForms, you can include a single JS library in a page, and then add a single block of <script> code that defines the validation rules to the bottom. In doing so, you inject validation into a form without the typical messy onClick/onSubmit garbage.


Inserting client-side validation logic is often messy and cumbersome.


Use the qForms JS library to inject your page(s) with standard and/or custom validation logic.

How qForms Works
The qForms API was designed principally to simplify the process of working with HTML forms via JavaScript. Typical uses of qForms include the following:

  • Easy getting/setting of form field values
  • Loosely-coupled form validation (stock validation, as well as custom validation)
  • Automatic event handling
  • Cookie management
  • And more...

While qForms offers many excellent features, this article focuses on its form validation capabilities.

Prep Work
The first thing to do is to download a copy of the qForms API. The latest stable release as of the time of this writing is version 1.5 (build 139). Although this build is two years old, the API is still relevant and effective, as qForms boasts an active user community.

Once you have the library files, set up a page that will enable you to use the API. To do this, load the base library and then initialize the API:


<script src="js/lib/qForms.js"></script>
<script type="text/javascript">
qFormAPI.setLibraryPath( "js/lib/" ); //set path to qForms library**
qFormAPI.include( "*" ); //load all default libraries
</script>

Author's Note: Be sure to place the qForms files in a directory structure that makes sense for your Web application. For this example, a folder named 'js' has been created with a subfolder named 'lib'. The qForms API and library files are then placed within the lib folder.

These initialization steps need to take place early in your page, ideally in the <head> section. With the qForms API initialized and its libraries loaded, you can move on to form validation.

Look Ma, No Events!
The most basic sort of validation you might want is forcing certain fields as required fields. In a typical implementation, this would require that you define event-handling routines via a single onSubmit method, or perhaps several onBlur/onFocus methods. You would then need to verify whether the required field(s) is/are not null.

With qForms, all you do is define a JS object with the same name as the form and then specify the required fields by name:


...
<form name="contactForm" action="/contactHandler">
<input type="text" name="firstname" />
<input type="text" name="lastname" />
<input type="text" name="phone" />
<input type="text" name="email" />
<input type="submit" />
</form>
...
<script type="text/javascript">
myContactForm = new qForm( "contactForm" );
myContactForm.required( "firstname, lastname, phone" );
</script>

When this page is served up and the form is submitted, client-side JavaScript logic will kick in and the qForms API will ensure that the required fields are completed prior to the form being submitted to the server. If these fields are not completed, an error message will appear to warn the user and the field or fields that have not been completed will be highlighted in red. All of this comes for free with the API and is fully customizable through the CSS.

For a live example of a simple form, check out Simple Form #1 from the qForms site.

More Form Validation
Requiring certain fields to have a value is a good starting point, but often applications demand more sophisticated validation capabilities. QForms rises to this challenge.

Out-of-the-Box Validation Methods
A variety of field validation methods come pre-built with qForms. To use these methods, simply reference the form and the form field name, and then call the method:


myForm.fieldName.validateXXX()

The following are just some of the validation methods qForms supports:


validateAlpha()
validateAlphaNumeric()
validateCreditCard()
validateDate()
validateEmail()
validateInteger()
validateLength()
validatePassword()
validatePhoneNumber()
validateSSN()
validateState()
validateZipCode()

Each of these methods also has an isXXX() version that returns a Boolean value and can be used in customized validation routines (described below).

Additional validation methods include the following:

  • createDependencyTo() The designated field is required only if the source field is selected/completed.
  • isNotNull()/isNotEmpty() Evaluate null and empty cases regardless of the field type (text, check/radio group, selection, and etc.).
  • validateAtLeastOne() List n number of fields, requiring at least one of them to be selected/completed.

Custom Validation Routines
Beyond its stock validation routines, qForms offers a rather extensive capability to define custom validation routines. This extensibility centers around two key methods:

  • validateExp() evaluates the supplied Boolean expression to determine a field's validity, such as verifying that a particular field is equal to a certain value, or ensuring that a field contains a certain number of characters
  • _addValidator() facilitates the creation of a fully customizable JS function that serves as a new Validator (complete with validateXXX() and isXXX() methods)

Time-Saving Form Validation
The qForms API is a simple, flexible JavaScript library that eases the development and maintenance of client-side JavaScript. In particular, qForms is an effective library for defining HTML form validation in a very lightweight, aspect-oriented manner. The next time that you are faced with the need for client-side validation of a Web form, give qForms a try. It just might reduce your development time and testing cycles, while leaving your forms clean and crisp.

Kyle Gabhart is a subject matter expert specializing in Service-Oriented technologies enabled by Java, .NET, and XML. Kyle's current post is as the Director of the SOA Division for Web Age Solutions, a premier provider of technology education and mentoring. He frequently speaks at technology conferences and writes for both online and print publications. Kyle blogs at www.soamatters.com.


qForms JavaScript API
The goal of the qForms API Project is to develop an open source programming library for interacting with HTML form elements. qForms is a complete JavaScript API for interfacing forms. The qForms API has been designed to make forms easy to use. It simplifies tasks HTML developers normally find tricky to handle.
Provider: PengoWorks.com   Cost: 0




JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM eBook: Planning a Service Oriented Architecture
IBM eBook: Choosing the Right Architecture--What It Means for You and Your Business
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Avaya Article: Using Intelligent Presence to Create Smarter Business Applications
Intel Go Parallel Article: Getting Started with TBB on Windows
Microsoft Article: 7.0, Microsoft's Lucky Version?
Avaya Article: How to Feed Data into the Avaya Event Processor
IBM Article: Developing a Software Policy for Your Organization
Microsoft Article: Managing Virtual Machines with Microsoft System Center
Intel Go Parallel Article: Intel Threading Tools and OpenMP
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
HP Video: StorageWorks EVA4400 and Oracle
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Red Gate Download: SQL Toolbelt and free High-Performance SQL Code eBook
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
Silverlight 2 App and Walkthrough: Leverage Silverlight 2 with SQL Server and XML
IBM Article: Enterprise Search--Do You Know What's Out There?
HP Demo: StorageWorks EVA4400
Microsoft Article: The Progress and Promise of Deep Zoom
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES