asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search








Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

How to Build a Forms Validation Library
By Edward Myers
Rating: 3.2 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Overview

    Developing HTML forms for entering or editing data on line is tedious and boring work. It is even more painful if you need a data-entry solution that supports both Netscape and Internet Explorer (IE). Thus most on-line forms have no JavaScript validation and barely any server validation.

    FormLib is a code framework that eliminates the tedious aspects of programming cross-browser client and server-side validation of input forms. This framework generates the validation code directly from the database structure and auto-fills the fields when editing an existing record. To use this framework one needs only to include one JavaScript and one ASP file into the page and have the form post the results to itself. FormLib simplifies form creation and eliminates common forms-maintenance tasks.

    The benefits of this approach will be clearer with an example. (Click to link to a sample form window.)

    Try changing values and notice the validation and in-field formatting of date, money, and phone fields. View the source to see the embedded validation code.

    The ASP code that produced this form is listed below.

    Code

    <!--#include file="FormLib.asp"-->
    <%
    PageNoCache
    ID=1*("0"&Request.QueryString("ID"))
    Action=ucase(Request.QueryString("Action"))
    set RS=ConnectToDB("Select * from PhoneBook where PhoneBookID=" & ID)
    if Action="SAVE" then
      ErrMsg= ValidateSQL(RS,"PhoneBook","") 
      if 0=len(ErrMsg) then
        ID=AddNewRecord(RS,"PhoneBook","PhoneBookID","")
        ConnectToDB(BuildSQL(RS,"PhoneBook","PhoneBookID=" & ID))
        Response.Redirect("NextPageInSequence.asp")
      else
        ErrMsg="<b>Warnings & Errors:</b>" & ErrMsg
      end if
    end if
    
    %>
    <html>
    <head>
    <title>PhoneBook Form</title>
    <script language="javascript" src=FormLib.js></script>
    <script language="javascript"><!--//
      function CustomValidation(FormObj){return(true);}
    //--></script>
    </head>
    <body bgcolor=white>
    <form METHOD="Post" ACTION="FormPage.asp?Action=Save&ID=<%=ID%>" 
      name=ContactForm onSubmit="return FormValidation(this)">
    <table cellspacing=0 cellpadding=0 width=400 border=0>
    <tr><td colspan=3><font color=red><%=ErrMsg%></font></td></tr>
    <tr><td><%=CheckBox(RS,"Status","Y","N")%> Active</td>
    <tr><td>Name:</td>
        <td><%=TextInput(RS,"FirstName",20,"")%></td>
        <td><%=TextInput(RS,"LastName",15,"")%></td></tr>
    <tr><tr><td>Address:</td>
        <td colspan=2><%=TextInput(RS,"Address",40,"")%></td></tr>
    <tr><tr><td>City/State/Zip:</td>
        <td colspan=2>
    <%    StateList=GetOptionList("","Select Abbrev from State") 
       Response.write TextInput(RS,"City",21,"") &_
                      OptionList(RS,"State",StateList,1) &_
                      TextInput(RS,"Zipcode",10,"notempty") 
    %>  </td></tr>
    <tr><tr><td></td>
        <td>Home:</td>
        <td>Work:</td></tr>
    <tr><td>Phone:</td>
        <td><%=TextInput(RS,"HomePhone",15,"Phone")%></td>
        <td><%=TextInput(RS,"WorkPhone",15,"Phone")%></td></tr>
    <tr><tr><td>Email:</td>
        <td colspan=2><%=TextInput(RS,"Email",40,"email")%></td></tr>
    <tr><td>Order Date/Amt:</td>
        <td><%=TextInput(RS,"LastOrderDate",10,"")%></td>
        <td><%=TextInput(RS,"LastOrderAmount",12,"")%></td></tr>    
    <tr><td colspan=2 align=right>
        <input type=submit name=go value=Save></td></tr>
    </table>
    <br>
    </form>
    </body>
    </html>
    <%CloseRS(RS)%>
    
    The virtue of this approach is there's less overall code and, therefore, smaller programs. Most of the complexity is hidden in the JavaScript and ASP include files. This allows junior-level programmers to modify and maintain forms without touching the core code. HTML coders can see the structure and rearrange the page without destroying the validation logic. Likewise, the database administrator can change the width or type of fields without requiring maintenance to the form validation.

    How Does It Work?

    Each of the input functions (e.g., TextInput, OptionList, and CheckBox) uses the information provided in the recordset object to output not only the HTML for input controls, but also the JavaScript validation code. The JavaScript code is placed in line with the HTML code. The in-line code is terse since it calls general validation routines stored in the JavaScript include file. Since the bulk of the validation routines is cached in the include file, form pages using this library are slimmer and load faster than typical forms.

    The onChange handlers for each input control are set so that validation is done immediately on data entry. During the validation the fields are reformatted with decorations. Dashes are added to phone fields, comma separators are added for large numbers, and dollar signs preceed money values. Textarea fields are checked to ensure that the user hasn't filled the control with too much text. The onSubmit handler repeats each of these validation routines in case the user ignores immediate validation warnings or forgets to fill in required fields.

    The server-side validation code is also auto-generated from the recordset when the form is posted back to itself. If errors are detected, the data saving is aborted and the form is redisplayed with the error text. The input controls are auto-filled with the value just posted and not the original value found in the database so the user can correct mistakes and repost.

    When the data is valid, the framework builds an SQL expression that updates the database. The SQL that is generated eliminates problems with single quotes in text fields, invalid dates in date fields, numbers too big for integer fields, or text strings too long for the database field. This eliminates the most common bugs found in custom-developed forms. If the entry is for a new record, it is automatically inserted before applying the update.

    To handle validation cases that are not apparent from the database structure, the forms programmer can add validation logic to a CustomValidation function that is executed both on the client and the server. Advanced programmers can extend the library by supplying regular expressions as field validation code.

    Here is a link to a downloadable zip file containing a complete example of the Myers FormLib,along with the source code for the ASP and JavaScript include files. Unpack the files into a PWS directory and then use your browser to display FormLibExample.asp. The example page illustrates using FormLib to build forms that contain data from multiple tables. It shows how to handle designs that use a primary table, a secondary category table, and a join table that matches a record in the primary table in a one-to-many relationship with the category table.

    About the Author

    Edward R. Myers, FormLib author, is an independant Web developer living in the Dulles Corridor of Northern Virginia. His current gig at Interealty.com provided the opportunity to apply this technique to real-estate Web sites containing many property-input forms. Ed can be reached by email at ed@myersfamily.com or visit his personal Web site (www.myersfamily.com) for current FormLib developments.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Other Articles
    Aug 7, 2002 - Using MySQL in the Win32 Environment
    Developers who don't want to spend a lot of money on SQL Server and who want a database that's more robust than Access may find MySQL to be a pleasant alternative. This introductory article covers the bare essentials for getting MySQL installed and running in the Win32 environment.
    [Read This Article]  [Top]
    Jul 17, 2002 - Software Development: Steps To Better Ensure Success
    There is never a guarantee of project success when endeavoring to build a sophisticated application. However, there are established steps to follow that will ensure a clear, concise scope, support for the team involved, and a solid opportunity for successful deployment.
    [Read This Article]  [Top]
    Jul 15, 2002 - Securing SQL Server for Web Applications
    If your SQL Server is exposed to the Internet, then hackers are probing it. This article shows how to secure a SQL Server database that's being used with a Web application
    [Read This Article]  [Top]
    Jul 1, 2002 - Protecting Your Web Application Against Dangerous Requests
    Enrico Di Cesare provides a solution for hiding and securing querystring values that pass through a url.
    [Read This Article]  [Top]
    Apr 2, 2002 - Object-Oriented Programming for VBScripters
    Feel intimidated by .NET? This article by Rob Chartier is designed to ease any level VBScripter (ASP) into .NET by clarifying some OOP concepts.
    [Read This Article]  [Top]
    Mar 27, 2002 - A Best Practice for Using ADO Objects
    A few members of the 15 Seconds discussion list talk about the proper way to use methods in order to prevent ADO object errors.
    [Read This Article]  [Top]
    Jan 2, 2002 - The ASP.NET Page Life Cycle
    Solomon Shaffer explores the life cycle of an ASP.NET page from initialization to unloading. He also explains the various methods to override ASP.NET server-side events.
    [Read This Article]  [Top]
    Dec 19, 2001 - Application Architecture: An N-Tier Approach - Part 2
    Rob Chartier creates a simple portable and reusable address book in .NET to demonstrate the power of N-tier application architecture. Complete source code included!
    [Read This Article]  [Top]
    Oct 23, 2001 - Application Architecture: An N-Tier Approach - Part 1
    Learn about N-tier application architecture and realize that developing with multiple layers produces a flexible and reusable application for distribution to any number of client interfaces.
    [Read This Article]  [Top]
    Oct 23, 2001 - Application Architecture: An N-Tier Approach - Part 1
    Learn about N-tier application architecture and realize that developing with multiple layers produces a flexible and reusable application for distribution to any number of client interfaces.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    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