JavaScript
  Home arrow JavaScript arrow Page 9 - Regular expressions in JavaScript
Moblin
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 
Moblin 
JMSL Numerical Library 
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 / 140
    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
     
     
    ADVERTISEMENT

    Get inside! Sample the range of functionality easily built with JMSL Library for Time Series Data Analysis, Heat Maps, Portfolio Optimization, Monte Carlo Simulation, Stock Price Charting and more. Download Now!

    Regular expressions in JavaScript - The test() method


    (Page 9 of 9 )

    The test() method is somewhat particular and different from the rest, as we’ll see shortly. Within the JavaScript context, when a pattern is defined following the syntax previously described, we are actually defining a new object, called a “regular expression object”. I don't  intend to go deeply into object programming concepts here. All we need to know is that this object owns the proprietary test() method, which allows us to perform string matching according to a given string.

    The test() method takes a given string as a parameter and looks for matches according to the pattern defined within the regular expression object itself. If any matches are found, it will return true. If no matches are found, then it will return false. Let’s see an example to explain how this method works:

    emailpat = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/;
    if( !mailpat.test( emailString ) ) {
     alert( ‘Please enter a valid email address’ );
    }

    First, we have defined a regular expression object that represents the standardized format of an email address. Then, we use the test() method to check for any matches to the email string passed as a parameter. If there are no matches, the error message will be displayed to the user.

    We can easily build a function to check for email address validity, as we have seen so many times:

    function validateEmail ( emailField, errorMsg ) {
     emailpat = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/;
     if( !emailpat.test( emailField.value ) ) {
      alert( errorMsg);
      emailField.focus();
      emailField.select();
      return false;
     }
     return true;
    }

    To validate an email address, we should call the function as:

    validateEmail( this.email , ‘Please enter a valid email address’ );

    where “this.email” is representing the form field named “email”. 

    Summing it up

    Having described the most common methods used with regular expressions, we can appreciate that they are not as intimidating as they seem. What’s more, we took a deeper look at their powerful capabilities for client-side validation, since they are an invaluable tool for verifying user input. By taking advantage of regular expressions in JavaScript, that verification can be done without making any requests to the server. 

    Validating user input prior to its being submitted is a good way to make sure that data are, at least, well formatted. However, JavaScript cannot be used on its own for complete validation, since it can be disabled in most browsers and offers limited control on user data. Server-side validation is always the best resource for complete and effective control.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · 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

    - Intergrate DWR into Your Java Web Application
    - Detect Browser Compatibility with the Reques...
    - Using the EXT JS Date Picker Widget
    - Ajax Hack for Entering Information Without R...
    - EXT JS 2.1 Overview
    - 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...







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