Click here to Skip to main content
15,890,512 members
Articles / Web Development / HTML
Tip/Trick

Using RegEx with Javascripts

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
30 Jun 2012CPOL 7.3K   3  
Using a Regular Expression within a Javascript to validate user input

Introduction

When you need to validate your users input in an HTML form, we all usually use JavaScript which is faster and light weight. But have you ever thought of how to include regular expression to validate input with JavaScript? Well here is a comprehensive example just for that. You can use RegExp object to achieve this objective. 

Using the code 

For this example let's say for a certain field we need to limit the user from entering special characters.

Following is the basic HTML code for the page.

HTML
<!DOCTYPE html>  
 <html>  
      <head>  
           <title>JS and RegEx</title>  
      </head>  
       <body>  
            <label for="txtUsername">Username</lable>  
           <input type="text" id="txtUsername" placeholder="Enter Username"/>  
      </body>  
 </html>  

In this particular page it will allow the user to enter anything as the username. But our requirement is to limit the user from entering special characters.

JavaScript
function ValidateInput(evt)  
 {  
   var valRegExp = new RegExp("^[a-zA-Z0-9]");  
   if (valRegExp.test(String.fromCharCode(evt.which)))  
   {  
       return true;  
   }  
   else  
   {  
       return false;  
   }  
 }   

Now you can see here in this function we have used valRegExp of type RegExp which allows us to create the regular expression. And we call the test method in valRegExp object to check if the entered character is allowed. String.fromCharCode method returns the character of the given ASCII code.

Full code is as follows.

HTML
<!DOCTYPE html>  
<pre> <html>  
      <head>  
           <title>JS and RegEx</title>  
           <script type="text/javascript">  
                function ValidateInput(evt)  
                {  
                  var valRegExp = new RegExp("^[a-zA-Z0-9]");  
                  if (valRegExp.test(String.fromCharCode(evt.which)))  
                  {  
                      return true;  
                  }  
                  else  
                  {  
                      return false;  
                  }  
                }  
           </script>  
      </head>  
      <body>  
           <label for="txtUsername">Username</lable>  
           <input type="text" id="txtUsername" placeholder="Enter Username" onkeypress="return ValidateInput(event)"/>  
      </body>  
 </html>   

Hope this helps. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Sri Lanka Sri Lanka
Software Developer with over 5 years of industry experience in .NET technologies.

Comments and Discussions

 
-- There are no messages in this forum --