How do I zero-pad a field in Infopath?

Sometimes it may be necessary to zero pad fields to get the correct upload and download results. However, InfoPath does not have an option to pad. To overcome this limitation, you can create a JavaScript to insert zeros, which you then publish with the InfoPath form. Use the instructions at the top of the following script to create your own script.

/*
 * This file contains a function for padding a field with leading zeroes.
 * It must be customized before it can be used, see the section below labeled:
 * "BEGIN CUSTOMIZE HERE"
 * For each field you want to pad there should be an 'if' block that matches 
 * the field name. When a match is found a call to myZeroPadField is made with the
 * second parameter indicating the final length of the padded string.
*/
==ShareVisBeginScript==

function SVFormXmlNodeChanged(theXmlNode, theChangedFormElementId)
{
  if (theXmlNode != null)
  {
    var theXPath = "//*[@SVFormElementId='" + theChangedFormElementId + "']";
    var theChangedNode = theXmlNode.selectSingleNode(theXPath);
    var theChangedNodeName = theChangedNode.getNodeName();

    // *** BEGIN CUSTOMIZE HERE ****
    if (theChangedNodeName == "my:field1")
    {
      myZeroPadField(theChangedNode, 10)
    }
    else if (theChangedNodeName == "my:field2")
    {
      myZeroPadField(theChangedNode, 5)
    }
    // *** END CUSTOMIZE HERE ****

  }
}


function myZeroPad(number, length) 
{   
    var str = '' + number;
    while (str.length < length) 
    {
        str = '0' + str;
    }   
    return str;
}

function myZeroPadField(theXmlNode, FinalSize)
{
  var theOldText = theXmlNode.getValue();
  if (theOldText != "")
  {
    var theNewText = myZeroPad(theOldText, FinalSize);
    if (theNewText != theOldText)
    {
      theXmlNode.setValue(theNewText);
    }
  }  
}

==ShareVisEndScript==

Previous Topic

Next Topic