Tuesday, June 13, 2017

InfoPath Force Input Format aka Mask

I had a need to force the format of a text input field to a pattern of 12 digits, three sets of four separated by dash i.e. XXXX-XXXX-XXXX.  Also, I wanted the user to be able to paste or type in their entry and the form automatically apply the format.  So if users typed in XXXXXXXXXXXX, the form would automatically apply dashes where needed.  Conversely, if a user typed XXXX XXXX XXXX, I need the spaces stripped out and dashes applied.

Research showed common solutions of creating a validation rule which would force the user to retype the data.  I did not agree with this solution as the form should really be smart enough to handle this simple task.  After research failed to provide an answer, I started experimenting. Long story short, I found a solution that works well enough for me.

First, create an action rule that removes spaces.
Condition:
  1. FIELD is not blank
Action:
  1. Set a field's value
  2. Field, should be the same field to which you are applying the rule
  3. Value is a formula: translate(FIELD, " ","")
This will remove any unwanted spaces

Second, create an action rule that adds dashes.
Condition:
  1. FIELD does not contain "-"
  2. FIELD is not blank
Action
  1. Set a field's value
  2. Field, should be the same field to which you are applying the rule
  3. Value is a formula: concat(substring(FIELD, 1, 4), "-", substring(FIELD, 5, 4), "-", substring(FIELD, 9, 4))
With these two rules, if a user types or pastes XXXXXXXX or XXXX XXXX XXXX or XXXX-XXXX-XXXX the field will be reset to the desired format of XXXX-XXXX-XXXX when focus moves to another field.  The only thing to note is any characters past 12 digits in this solution will be truncated.

This solution should be scalable to any need where you require a specific format to text.