BCS Javascript Format Phone Number

There are those times when formatting data as it appears on a form is required for ease of reading and ease of use. This example show how to format a telephone number.

First we will look at the script itself.

<script type="text/javascript">
<!--
function textBoxOnBlur(elementRef)
{
 //5754578787, it should be 575-457-8787
 
 var elementValue = elementRef.value;
 
 // Remove all "(", ")", "-", and spaces...
 elementValue = elementValue.replace(/\(/g, '');
 elementValue = elementValue.replace(/\)/g, '');
 elementValue = elementValue.replace(/\-/g, '');
 elementValue = elementValue.replace(/\s+/g, '')
 
 if ( elementValue.length < 10 )
 {
  alert('The phone number needs 10 characters');
  elementRef.select();
  elementRef.focus();
  return;
 }
 
 elementRef.value = ('(' + elementValue.substr(0, 3) + ') ' + elementValue.substr(3, 3) + '-' + elementValue.substr(6, 4) + '*');
}
// -->
</script>

Then we will examine the code that implements the field formatter.

<input name=”tf01″ type=”text” value=”5734747417″ size=”15″ onblur=”textBoxOnBlur(this);” onfocus=”textBoxOnBlur(this);”/>

In this example the onblur and onfocus events invoke the field formatting.  Of course you can attach the formatter to any desired event using the above syntax.

The field 5734747417 is formatted and appears on the screen as (573) 474-7417.

Of course this code could be modified to format a SSAN as well as any formatting of almost any field.

Of course this technique will function for any technology that support JavaScript.

Mr. Arch Brooks, Software Engineer, Brooks Computing Systems authored this article.