Skip to main content
Kinetic Community

Correcting Format Instead of Generating Validation Error

This type of solution is helpful if you'd like to correct a format instead of erroring.

Usage

This type of solution is helpful if you'd like to correct a format instead of erroring. This is particularly helpful with phone numbers. They often need to be entered in systems in a particular format, but there are many different generally acceptable formats. A user may enter

(555) 555-1212

555.555.1212

555-555-1212

5555551212

But, in this example, the only acceptable format is 555-555-1212. The technique used here is to strip all the user entered formatting so that only numbers are left. Then the desired format can be applied. This needs to be called any time the phone number field(s) are changed (and not emptied).

Example

This is an example of the custom change event is on a question called OfficePhone.

CorrectPhoneNumberEvent.png

This correctPhone function can be called for multiple phone questions on the same service item (ex. OfficePhone, MobilePhone)

function correctPhone(PhoneQuestionName)
{
   var phone = KD.utils.Action.getQuestionValue(PhoneQuestionName);
   KD.utils.Action.setQuestionValue(PhoneQuestionName, formatPhone(phone, PhoneQuestionName));
}

The formatPhone function performs the work of doing the correction.

function formatPhone(elementValue, PhoneQuestionName)
{
//5754578787 or (575) 457-8787, it should be 575-457-8787

// Strip all likely extra characters so we can start
// from scratch in adding our own formatting
// Remove all "(", ")", "-", "." and spaces...
elementValue = elementValue.replace(/\(/g, '');
elementValue = elementValue.replace(/\)/g, '');
elementValue = elementValue.replace(/\-/g, '');
elementValue = elementValue.replace(/\./g, '');
elementValue = elementValue.replace(/\s+/g, '');

// Validate the correct number of digit was entered
if ( elementValue.length != 10 && elementValue.length != 0)
{ //alert and turn the focus to the problem field
  alert('The phone number needs 10 characters');
  KD.utils.Util.getElementObject(PhoneQuestionName, 'SRVQSTN_').focus();
  return;
}

// Apply the desired formatting
var HREF = elementValue.substr(0, 3) + "-" + elementValue.substr(3, 3) + "-" + elementValue.substr(6, 4);
return HREF;

}