29
Fri, Nov
0 New Articles

Form Follows Function: HTML Form Validation with JavaScript

Scripting
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Our neighbor once asked my wife how her husband could be traveling all over the country teaching Java. He figures he, a nonprogrammer, taught himself JavaScript in a couple of weekends, so why would programmers travel somewhere to learn Java or JavaScript (or whatever they call it)? Well, my neighbor—or anyone else for that matter—is not going to be developing an accounts payable system in JavaScript soon, but a good programmer can develop an A/P system in Java.

The point is that JavaScript is not Java. JavaScript is a small interpreted scripting language that runs in the context of a browser. JavaScript’s most common use is to jazz up user interfaces and perform simple validation of user input. Java, as with RPG and COBOL, is a complete, compiled programming language that professional programmers use to build entire applications.

Originally, JavaScript was called LiveScript. When Netscape, the LiveScript creators , first introduced its new scripting language, no one cared; but, when Netscape’s marketing department renamed LiveScript to JavaScript, Netscape’s stock jumped $20 in one day.

Valifying Data (or Validate and Verify)

You can do a lot of cool things with JavaScript to liven up your Web pages. Personally, I leave that stuff to Web developers. For me, a business programmer, all I want JavaScript to do is validate HTML input fields on the browser. The trick to developing Web applications that perform well is to use the Internet as little as possible. A Web application that passes data from an HTML input form to a server-side application program is inefficient if the server-side application responds with “invalid date” or “quantity must be entered.” This is true if it’s an AS/400 RPG CGI program, cross-platform Java servlet, or a Microsoft Active Server Page (ASP).

Simple editing of HTML input fields can be done on the client-side of the application by the browser using JavaScript, and this article shows you how easy it is.

Figure 1 (page 79) shows a simple address input form. The user entered his address but keyed the wrong state abbreviation. The pop-up window at the top of the form


informs the user of the inappropriate value. Figure 2 shows the HTML file that contains the HTML input form in Figure 1, as well as the JavaScript that edits that form. (For more on HTML forms, see “In the HTML Driver’s Seat” by Teresa Pelkie, MC, December 1999.)

On Submit

The form statement includes an option called onSubmit. Qualifying the onSubmit option with the return keyword and the name of a JavaScript function creates a link between an HTML input form and a JavaScript edit function. The keyword this, by the way, simply means the validate function is passed the form data from the current form. If an AS/400 systems programmer had designed JavaScript, he would have probably used *CURRENT instead.

The code for the validate function in Figure 2 immediately follows the HTML form. Notice that the validate function is embedded to the HTML document. That means that, as with standard HTML, the browser is responsible for parsing the JavaScript code. The JavaScript function is wrapped by a set of script tags. The opening tag identifies the language as JavaScript. Many browsers support several scripting languages. You might, for instance, use VBScript (although that would limit your clients to those with Internet Explorer [IE]). Since both Netscape Navigator and Microsoft Internet Explorer support JavaScript, I recommend you stick with JavaScript. If you think your client base may not be running Netscape 2.x or IE 3.x or higher, you should add the comment line that follows the opening tag:

Those two lines effectively hide the JavaScript code from browsers that don’t support JavaScript.

Mandatory Code

The validate routine begins by defining and initializing a set of variables. Notice that the parameter to the function, called form, is a handle to all the input values from the HTML form. The function retrieves values from input fields by qualifying the field name with the form parameter name and then asking for its value. For instance, to set the value of the city variable, I used the following statement:

var city = form.city.value;

The validate function then checks to see if the mandatory fill fields contain data. The exclamation point is a NOT operator so !firstName is a Boolean condition that evaluates to true when no value is entered for the HTML form’s first name field (but firstName != “” would work just as well). The bodies of the mandatory fill conditional statements all position the cursor to the form field and then append an error statement to the errorMessage string. After all mandatory fill fields are checked, the following block of code pops up an error window if the errorMessage contains any data:

if (errorMessage != “”) {

errorMessage = “Required field: “ + errorMessage;

alert(errorMessage);

return false;

}


The alert function popped up the error window shown in Figure 1. The return statement forces the validate function to exit, and, when it returns false, it tells the browser not to send the invalid HTML input data to the server for processing.

Numbers and Arrays

The code for validating the state code illustrates how you can use arrays in JavaScript, although it would be better if the form contained a select list for state. To declare an array, you initialize its value with a comma-separated list. The states array is all uppercase, so the validate function uses JavaScript’s toUpperCase function to convert the user-entered state code to uppercase. The indexOf function, which is automatically available to any array and is comparable to RPG’s lookup opcode, is then executed on the states array passing the uppercase value of the state code. When the indexOf function returns negative one, you know the user entered an invalid state.

The value of a form variable can be modified with a JavaScript method as shown in the following statement to force uppercase state code.

form.state.value = upState;

The ZIP code is validated by checking two steps: First by making sure that it is a number using the isNaN function; and second, that the number is either five or nine digits long.

Birth dates are sensitive pieces of information, so the date routine validates only if year, month, or day is entered. I use the parseInt function, which ignores non-numeric characters, to convert the string value entered by the user into an integer before I perform some simple date edits. You may want to strengthen this routine further to handle things like leap year and the number of days in a particular month.

Last Minute Tips

Let me leave you with a few last minute tips. First, to debug your JavaScript, make liberal use of alerts. Second, take advantage of modular-programming techniques by putting your JavaScript routines into separate files then including them in your HTML files with the src option of the SCRIPT tag:

Third, test your JavaScript code on both Netscape and IE because scripts may behave differently on the various browsers. Both Netscape and IE have tempting extensions to the base JavaScript language, which was standardized last year by the European Computer Manufacturers Association (ECMA) as ECMAScript, that do not work on competitors’ browsers. For more information on JavaScript, visit the Web sites listed in the References and Related Materials list.

REFERENCES AND RELATED MATERIALS

• “e-RPG: Building AS/400 Web Applications with RPG” by Bradley V. Stone, Midrange Computing (www.mc-store.com/mc-store)

• Internet.com’s JavaScript Tip Archive: webreference.com/js/tips/browse. html

• Internet.com’s Validate page: webreference.com/authoring/languages/ html/validation.html

• Microsoft Windows Script Technologies Web site: wmsdn.microsoft.com/scripting/


• Sun Microsystems/Netscape Communications Alliance Java Script Sample Code Web site: developer.netscape.com/tech/javascript/index.html?content=/docs/examples/ javascript.html

Form_Follows_Function-_HTML_Form_Validation...204-00.png 400x308

Figure 1: Basic editing of dates, codes, and mandatory fill fields should be performed on the client not on the server.

Form Validation with JavaScript

onSubmit="return validate(this)">

Name and Address:

 

 

 



,  

   


Birthdate (MM/DD/YY):  

/

/




Figure 2: JavaScript is embedded into HTML. It is parsed and interpreted by the Web browser not the Web server.


Don Denoncourt

Don Denoncourt is a freelance consultant. He can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Don Denoncourt available now on the MC Press Bookstore.

Java Application Strategies for iSeries and AS/400 Java Application Strategies for iSeries and AS/400
Explore the realities of using Java to develop real-world OS/400 applications.
List Price $89.00

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: