SunQuest
 
       JavaScript
  Home arrow JavaScript arrow Page 7 - Regular expressions in JavaScript
IBM developerWorks
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Actuate Whitepapers 
VeriSign Whitepapers 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVASCRIPT

Regular expressions in JavaScript
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 138
    2004-12-20

    Table of Contents:
  • Regular expressions in JavaScript
  • The Basics
  • Character Escaping
  • Repetition
  • Counted Subexpressions
  • Using regular expressions in JavaScript
  • The match() method
  • The replace() method
  • The test() method

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
    Iron Speed
     
    ADVERTISEMENT

    At the virtual BlackBerry Technical Seminar 2008, you can ask your development questions directly of Research In Motion® (RIM) experts, and take advantage of learning opportunities designed uniquely for BlackBerry solution developers. Register Today!

    Regular expressions in JavaScript - The match() method


    (Page 7 of 9 )

    The match() method takes a regular expression as a parameter and returns an array of all the matching strings found in the string given. If no matches are found, then match() returns false. Let’s say we want to check the proper format for a phone number entered by a user, with the form of  (XXX) XXX-XXXX. The code listed below does that:

    function checkPhone( phone ) {
      phoneRegex = /^\(\d\d\d\) \d\d\d-\d\d\d\d$/;
     if( !phone.match( phoneRegex ) ) {
      alert( ‘Please enter a valid phone number’ );
      return false;
     }
     return true;
    }

    Let’s break down the code to understand how it works. First, we define a function that will check if the phone number entered has a valid format. Next, we declare the regular expression to define our pattern. It begins with ^, to indicate that any match must begin at the start of the string. Then we have \(, which will match the opening parenthesis. As seen previously, the character is escaped with a backslash to remove its special meaning in regular expression syntax. As mentioned, \d is a special code that matches any digit. The expression \d\d\d matches any three digits (same effect is achieved with [0-9] [0-9] [0-9]).

    The rest of the pattern is pretty easy to understand. \) matches the closing parenthesis, the space matches the proper space for the phone number, then \d\d\d-\d\d\d\d matches three any digits followed by a dash, and then followed by four any digits.Finally, the $ indicates that any match must end at the end of the string.

    It’s possible to short the regular expression as follows:

    phoneRegex = /^\(\d{3]\) \d{3}-\d{4}$/;

    Once we have seen in detail the regular expression pattern, let’s see how our function works. It checks whether or not the string contained in phone, passed as a parameter, matches our regular expression. If it does, then an array will be returned which JavaScript will evaluate as true. Otherwise it will return false, displaying the proper error message to the user.This kind of function is commonly used to validate user input data coming from HTML forms, chaining several specific functions to check if data entered is valid or not.

    Here is an example:

    First, the JavaScript code located in the HEAD section (or even better, in a separate .js file)

    <script language=”javascript”>
    validateForm = function() {
     if ( checkPhone( this.phone, ‘Please enter a valid phone number’ ) ) {
      return true;
     }
     return false;
    }
    checkPhone= function( field, errorMsg) {
      phoneRegex = /^\(\d{3]\) \d{3}-\d{4}$/;
      if( !field.match( phoneRegex ) ) {
      alert( errorMsg );
      field.focus();
      field.select();
      return false;
     }
     return true;
    }
    signupForm = document.forms[0];   // assumes that it’s the first form present in the document
    signupForm.onsubmit = validateForm;
    </script>


    And the HTML form code is the following:

    <form action=”signup.htm”>
    <p>Phone number ( e.g. (123) 456-7890):<input type=”text” name=”phone” /></p>
    <p><input type=”submit” value=”send” /></p>
    </form>

    The user will be unable to submit this form unless a valid phone number has been entered. If the number format is not valid, an error message will be displayed (generated by our validateForm function).

    As stated above, it’s easy to add more functionality to our validateForm() function. If we want to apply more than one check to the form, we can embed several calls to specific functions to perform particular validation, achieving something like this:

    validateForm=function () {
     if ( checkPhone( this.phone, ‘Please enter a valid phone number’ ) && checkEmail( this.email, ’Please enter a valid email address’ ) ) {
      return true;
     }
     return false;

    The code is very compact and is separated completely from the HTML.

    Next, it’s time to see another useful JavaScript method for working with regular expressions: the replace() method.

    More JavaScript Articles
    More By Alejandro Gervasio


       · The phone number validation code does not work per the article. Not only that, but...
       · my code did not cut and paste well as you can see above. You may test it out on my...
       · Sorry it took me so long to reply back.Your commnents is always welcome. The...
       · Hi again,I checked your code at your server and it's working just fine....
       · hitiy need to change the quotes from `eg validateEmail( this.email , `Please...
       · Yes, there is an error about the quotes. Due to program incompatibility.Just...
       · Yes, there is an error about the quotes. Due to program incompatibility.Just...
       · In the code a ] was inadvertenly placed instead of a }. Probably a typo - forgot to...
       · Hi Htarko,Thank you for commenting on this article, and of course thank you for...
       · I read your article.. It's fine.. But I couldn't find the regular expression for...
       · Thank you for commenting on my JavaScript article. Regarding your question, you can...
     

    JAVASCRIPT ARTICLES

    - Using the Style Object for Zebra Tables with...
    - Binary Searching
    - An Improved Approach to Building Zebra Tables
    - Assigning Background Colors Dynamically to Z...
    - Building Zebra Tables with CSS and JavaScript
    - JavaScript: Array Objects
    - A Closer Look at Smart Markers with Yahoo! M...
    - Using Polylines and Smart Markers with Yahoo...
    - Bulleted Menu of Links
    - Creating Click Loggers and Basic Markers wit...
    - Adding Pan Controls to Yahoo! Maps
    - Adding Zoom Controls to Yahoo! Maps
    - Working with Yahoo! Maps
    - Building Image Zooming Controls with the DOM...
    - Working with Multiple Graphics for a Zoom Ap...

    Iron Speed

    Iron Speed





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway