Thursday, August 14, 2008

Creating CRM Field Mask / Format

Yet another feature i would like to see MS provide out of the box. Quite simple to implement.
Call the Mask function providing the field id and mask (# acts as a placeholder) and you're done.
The end user only has to fill in the numbers e.g. 97356568987




function OnCrmPageLoad()
{
Mask( "telephone2" , "+(###)-(#)###-###" );
Mask( "gi_visa" , "####-####-####-####" );
Mask( "gi_scid" , "#-########-#" );
}


function Mask( fieldId , mask )
{
field = document.getElementById(fieldId);
field.mask = mask.split("");
field.regex = new RegExp(escapeRegEx(mask.replace(/#/gi,"").split("")),"gi");
field.title += " " + mask;
field.attachEvent( "onchange" , MaskOnFieldChange );
}

function escapeRegEx( chars )
{
var regChars = "+_)(*^$[]-?{}"; //Add all regexp chars id needed
var regExprs = "";
var run2Index = chars.length - 1;

for( var i = 0 ; i < run2Index ; i++ ) Concat( chars[i] , "|" );


Concat(chars[run2Index]);


function Concat( c , d ){
regExprs += (( regChars.indexOf(c) != -1 )? "\\":"" ) + c + d;
}

return regExprs;
}


function MaskOnFieldChange()
{
var field = event.srcElement;
if( field.DataValue == null ) return;

var arrDataValue = field.DataValue.replace(field.regex,"").split("");
var arrResult = [];

for(var i=0 , j=0 ; i < field.mask.length ;i++)
arrResult[i] = (field.mask[i] != "#")?field.mask[i]:arrDataValue[j++];

field.DataValue = arrResult.join("");
}

OnCrmPageLoad();

1 comment:

Anonymous said...

Well... your code does not seem to work for the onchange event of the field...