spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / experts / javascript / column5


JavaScript Regular Expressions

Developer News
Mandrake Linux Founder Back, Virtually
Amazon: We're a Technology Company
Sun Expands MySQL With Closed Source

A Feedback Form

In this section we'll show you how to create a feeback form that checks if the user's e-mail address' syntax is valid. We'll first provide the script, and then explain it in depth. The final result looks like this:

Your e-mail address:

Subject:

Comments:

Enter a string in the "e-mail" field, and submit the form. If your string is a valid e-mail address, the script accepts it (and would submit the form, but this is just a demo). If the string is not a valid e-mail address, a message is displayed and the field is highlighted for easy correction. Note that this specific form does not send me an e-mail, because it's just a demo! Here's the code for this form and its corresponding script:

If you're using a browser that doesn't support regular expressions, you'll get an immediate error. In the following section we'll show you how to solve this problem.

<SCRIPT LANGUAGE="JavaScript">
<!--

function valid(form) {
  var field = form.email; // email field
  var str = field.value; // email string
  var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
  var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid
  if (!reg1.test(str) && reg2.test(str)) { // if syntax is valid
    alert("Thank your for your feedback."); // this is optional
    return true;
  }
  alert("\"" + str + "\" is an invalid e-mail!"); // this is also optional
  field.focus();
  field.select();
  return false;
}

// -->
</SCRIPT>
<FORM METHOD="POST"
      ACTION="mailto:you@yourdomain.com"
      ENCTYPE="text/plain"
      onSubmit="return valid(this)">
Your e-mail address:<BR><INPUT TYPE="text" NAME="email" SIZE="40"><BR>
Subject:<BR><INPUT TYPE="text" NAME="subject" SIZE="40"><BR>
Comments:<BR><TEXTAREA NAME="comments" COLS="40" ROWS="5"></TEXTAREA><BR>
<INPUT TYPE="submit" VALUE="Send Mail">
</FORM>

Take a look at the <FORM> tag, which defines the form's main attributes. You should change the e-mail address to your own, so the user sends you an e-mail when he or she submits the form. The onSubmit event handler provides the ability to cancel the submission if it returns false. The statement return valid(this) simply returns the value that is returned by the valid() function. If the function returns false (it does that when the user's e-mail address has an invalid syntax) the form's submission is cancelled. Otherwise, the submission proceeds. The term this in the event handler refers to the form (it's actually a JavaScript object that reflects the form), so this.email, for example, would refer to the field named "email".

Now let's see how the function works, and what it does. First, it assigns the variable field an object that reflects the e-mail address field. The value of this field is then assigned to the variable str. The function then defines two regular expressions: reg1 and reg2. The first one matches common invalid e-mail addresses, whereas the second one matches the general e-mail address syntax. By combining these two expressions (we negate the first one, of course) we achieve a relatively reliable e-mail verification mechanism.

The function utilizes a simple if statement to check if the e-mail address' syntax is valid. If so, it displays a message and returns true, so you (you@yourdomain.com) receive the user's e-mail. Otherwise, an alert is displayed and the e-mail address field is highlighted, so the user can easily edit the address. The function then returns false, cancelling the submission.

The first regular expression is very obvious, but the second one is a bit more difficult. It matches the basic syntax of an e-mail address, according to the following rules (in order of appearance):

  1. One or more characters before the "@"
  2. An optional "[", because user@[255.255.255.0] is a valid e-mail
  3. A sequence of letters, numbers, and periods, which are all valid domain or IP address characters
  4. A period followed by a 2-3 letter suffix
  5. An optional "]"

http://www.internet.com

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

Whitepapers and eBooks

Intel Whitepaper: Comparing Two- and Four-Socket Platforms for Server Virtualization
IBM Solutions Brief: Go Green With IBM System xTM And Intel
HP eBook: Simplifying SQL Server Management
IBM Contest: Are You the Next Superstar? Join the "Search for the XML Superstar" Contest to Find Out
Microsoft PDF: Top 10 Reasons to Move to Server Virtualization with Hyper-V
Microsoft PDF: Six Reasons Why Microsoft's Hyper-V Will Overtake Vmware
Microsoft Step-by-Step Guide: Hyper-V and Failover Clustering
Intel PDF: Quad-Core Impacts More Than the Data Center
Intel PDF: Virtualization Delivers Data Center Efficiency
Go Parallel Article: PDC 2008 in Review
Microsoft PDF: Top 11 Reasons to Upgrade to Windows Server 2008
Avaya Article: Communication-Enabled Mashups: Empowering Both Business Owners and IT
Intel Whitepaper: Building a Real-World Model to Assess Virtualization Platforms
  PDF: Intel Centrino Duo Processor Technology with Intel Core2 Duo Processor
Microsoft Article: Build and Run Virtual Machines with Hyper-V Server 2008
Go Parallel Article: Q&A with a TBB Junkie
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
IBM eBook: The Pros and Cons of Outsourcing
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
HP eBook: Guide to Storage Networking
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
webref The latest from WebReference.com Browse >
Popular JavaScript Framework Libraries: An Overview - Part 3 · Accessing Your MySQL Database from the Web with PHP · Working with the DOM Stylesheets Collection
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Crucial Triples Up With New Three-Channel DDR3 Kits · Meet the Finalists: Excellence in Technology Awards · Tealeaf Offers Insight to Mobile Customer Behavior

Created: October 23, 1997, 1997
Revised: December 4, 1997
URL: http://www.webreference.com/js/column5/form.html