Thursday, April 4, 2013

Useful tool for creating Regular Expressions

I needed to create a regular expression in javascript to validate a textbox where I was using typeahead to populate the data.    If the user entered garbage the typeahead data would go away and the garbage would stay.

I decided to use a RegEx to fix this issue, but honestly I was not all that familiar with them.   I had used them in years past, but just copied and pasted ones created by someone else.   In this case, I had to create my own expression.

I tried reading up on them in my javascript book: Javascript for Web Developers, but I just wasn't getting it.   I then remembered that there was a video training course on Lynda.com that covered RegEx.   The whole course is over five hours, but I was able to get what I needed in the first 4 chapters.   The teacher really helps to make sense of them.  (You will need to be a subscriber to see videos)

In the course, he recommends the tool Regex Pal, as a means of testing your expressions.   It is very simple and easy to use and a good tool in the toolbox.  The format is standard across all major programming languages.

Here is the finished clientside javascript that I added to my application.  The tool helped me to generate the second line, and allow me to paste actual data to test that the expression correctly matches.

var x=document.getElementById("#{id:inputText2}").value;
var expression = /.* - .* - .*/;  //regex matching vendor format

if (expression.test(x)=== false)
{
   alert("Please choose proper Vendor Name from the dropdown list.");
   document.getElementById("#{id:inputText2}").value = "";
   document.getElementById("#{id:inputText2}").focus();
   return false;

No comments:

Post a Comment