Greg's Blog

helping me remember what I figure out

JavaScript: Using Regular Expressions to Search and Replace (IE4)

| Comments

As part of a project I wanted to grab the form field name and use it to display error messages. No problem there, but as most of you know form field names can at times be rather cryptic so I decided on choosing a naming convention that would allow me to use Regular Expressions to strip out the following information: required, field name and the error message to be displayed. The format for I choose looked like this: r_field#_?Your_error_message?, where you use r_ to indicate required and o_ for optional. Field# is used to give the field name a unique value. The last bit is pretty straight forward between the single quotes you store the error message you want displayed.

In the following I will talk you through writing a script that extrapolates the error message, replaces the "_" with a space, removes the single quotes and writes the error message to the page. Ready? Well let?s take a look at the whole script:

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
<html>
<head>
<title>Example match and replace</title>
<script language=”JavaScript1.2”>
function strip(f) {
   for (var i=0;i<f.length;i++) {
      e = f.elements[i];
      var ar = e.name.match(/(w+)?([^# ]*)/);
      var str = RegExp.$2.replace(/_|’/g, ’ ‘);
      if(((e.type == “text”) || (e.type == “textarea”)) && !e.optional) {
         if ((e.value == null) || (e.value == “”)) {
         whichEl = eval(“document.all.elField” + i);
         whichEl.innerHTML = str;
         }
      }
   }
   return false;
}
</script>
</head>
<body>
<form name=”form1” action=”” method=”post” enctype=”multipart/form-data” onsubmit=”return strip(this);”>
<input type=”Text” name=”r_test1_’test_1’” size=”25”>  <SPAN ID=”elField0”></SPAN><br>
<input type=”Text” name=”r_test2_’test_2’” size=”25”>  <SPAN ID=”elField1”></SPAN><br>
<input type=”Submit” name=”sub_but_2” value=”Submit”>  <SPAN ID=”elField2”></SPAN>
</form>
</body>
</html>

Not too long is it? Ok the form is pretty standard and the JavaScript function strip(this) is called once the form is submitted. I also appended a <span> to each form field as this is where the error message is going to be displayed (should an error occur).

Now onto the script, first we start off by looping over all the form elements. Next to reduce typing I declared a variable e that stores the individual form element for each loop. Next I broke down the field name (e.name) using the match() function and storing the substrings. As a result the error message gets stored in RegExp.$2 [RegExp.$# is a property associated with Regular Expressions that are available to the developer, for more information follow the link on the right hand side on Regular Expressions]. Moving along, next we are going to use the replace() function on RegExp.$2 and remove the "_" and the single quotes. To this end we define a pattern to be replaced as follows: /_|?/g. and this pattern will be replaced with: ? ? (that?s right a blank space). The result of this we store in a variable called str.

The next step in the script involves checking the content of the form fields, in this case for each form element it checks whether or not the form element type is either a text field or a text area field and whether or not it?s optional (not used in this script). If the field is of type text, the script then checks to see if these have been completed or not. In our example all fields are required, so leaving them blank and submitting the form will result in an error message being generated. At this stage we need to figure out where the error message is going to appear, this is where the <span> comes in. Each tag has an ID called elField#, where # is a sequential number starting with zero, hence the first form element will have the following <span> ID: elField0. Using the loop value i we evaluate the position which for the first element is 0 and set whichEl to that value. Next we tell the script to write (whichEl.innerHTML) the error message to that <span> ID.

You may be wondering why I included the Regular Expression part of the script at the top of the script and not when it is required such as when a field is left blank, which would have been more efficient, however I was more concerned with page weight and didn?t want to have to include the same statement over and over again for each type of form field. Based on that assumption maybe I could create a function and just pass the field name at that stage to the function, this would both cut down on space and make for a more efficient program. I?ll let you know. In the meantime I hope you find this useful.