7.1. Preventing Blank Form Fields

Problem

You need to make sure visitors to your site fill in all the required fields in your web site form.

Solution

Use the onBlur, onClick, or onSubmit JavaScript event handlers in your form to check for empty fields before the form data is sent to the server.

Discussion

A well-written PHP or CGI script will check the data it gets from a web form before it performs its actions on it. If required fields are missing, the script should show the user an error page, rather than saving incomplete information in a database.

Error-checking in your server-side scripts requires a hit on your web server and causes your user to wait; you can head off an unnecessary connection by checking form data before it gets sent. Testing required fields for a value with JavaScript will save time and processing resources on your server:

	<form action="form.php" method="post">
	<fieldset>
	<legend>&#x260E; Contact Information</legend>
	 <h3>Name *</h3>
	  <input name="name" type="text" size="20" maxlength="20" tabindex="1"
	   onBlur="if(this.form.name.value=='')
	       {alert('Please fill in your first and last name.')};">
	 <h3>Email Address *</h3>
	  <input name="email" type="text" size="20" maxlength="20" tabindex="2"
	   onBlur="if(this.form.email.value=='')
	      {alert('Please fill in your email address.')};">
	 <h3>Phone Number *</h3>
	  <input name="phone" type="text" size="12" maxlength="12" tabindex="3"
	   onBlur="if(this.form.phone.value=='')
	      {alert('Please fill in your phone number.')};"><br> <input name="Send" ...

Get Web Site Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.