Hi Kathy,
As a strictly US company, we use something pretty simple: Stripping out everything but numbers, verifying that there are 10 digits, and re-inserting the proper format dashes so ours are all formatted ###-###-####. This 1) is still using the old model with Xrm.Page, so not ideal for copying. 2) Could be expanded to check for additional formats / countries. Still, the basic use of a string.replace function with a regular expression has worked well for us.
function FormatPhoneNumber(FieldName) {
var PhoneControl = Xrm.Page.getAttribute(FieldName).controls.get(0);
var PhoneControlLabel = PhoneControl.getLabel();
var PhoneNumber = Xrm.Page.getAttribute(FieldName).getValue();
if (PhoneNumber !== null) {
PhoneNumber = PhoneNumber.replace(/[^0-9]/g, "");
switch (PhoneNumber.length) {
case 10:
PhoneNumber = PhoneNumber.substr(0, 3) + "-" + PhoneNumber.substr(3, 3) + "-" + PhoneNumber.substr(6.4);
Xrm.Page.getAttribute(FieldName).setValue(PhoneNumber);
break;
default:
alert("\n\n Ah ah ah. You didn't say the magic word. \n\n\n " + PhoneControlLabel + " must contain 10 digits.\n");
}
}
}
You may note, I grabbed the phone label so I could tell the user exactly which phone number had issues.
Also, this doesn't force the user to make the change / delete the value if formatting is wrong. Deleting the value seemed like a bad move as the user may lose it altogether. We could have put in code to prevent the save, but instead just set this to fire frequently, so users would be reminded multiple times if they didn't immediately address the formatting error. This has worked well.
------------------------------
Ryan Perry
Auric Solar
West Valley City UT
------------------------------
Original Message:
Sent: 11-16-2018 06:54 AM
From: Kathy Anderson
Subject: formatting phone number
I've researched various options to format a phone number text field a certain way (EX: 555-444-3333, (555)444-3333, etc). I'd like input on what method you have used. Does your option take into consideration the country? What have you tried and would not suggestion? Any input on the best practice is appreciated.
------------------------------
Kathy Anderson
IT Project Mgr
Milton CAT
Londonderry NH
------------------------------