15 Apr
Posted by: mitch in: Customization, Dynamics CRM
In the CRM 3.0 SDK, you will find an example of how to use an Attribute's OnChange event to format a phone number. We found a bug in this code that was quite interesting.
1) Enter a valid phone number and exit the field so that the OnChange Event fires and the phone number is formatted.
2) Change focus back to the phone number field and erase the entire phone number.
3) Press Tab to leave the field.
At this point you should get a JavaScript error in the OnChange event complaining about the DataValue property.
It would appear that since the field had once contained valid data, it was not undefined and not null. Both of these two conditions were checked by the code and since both were not true, it continued on with the format routine. The problem seems to be that when we removed the data from the field, the DataBalue property was disposed of, which later caused an error when we attempted to access the contents of the property.
I added an extra check to make sure the DataValue property was not null before I started my validation and formatting operation. Code is highlighted below:
// Attempt to auto-format basic US phone numbers. This method supports // 7 and 10 digit numbers. Example: (410) 555-1212 // Get the field that fired the event var oField = event.srcElement; // If we have the field and all is well if (typeof(oField) != "undefined" && oField != null) { if (oField.DataValue != null) { // Remove any non-numeric characters var sTmp = oField.DataValue.replace(/[^0-9]/g, ""); // If the number is a length we expect and support, //format the number switch (sTmp.length) { case "4105551212".length: oField.DataValue = "(" + sTmp.substr(0, 3) + ") " + sTmp.substr(3, 3) + "-" + sTmp.substr(6, 4); break; case "5551212".length: oField.DataValue = sTmp.substr(0, 3) + "-" + sTmp.substr(3, 4); break; } } }
2 Responses
Anne Stanton
25|Apr|2008 1Thanks Mitch! I often have users ask for this one and some of them are tiny, with development resources.
Format telephone field in CRM 4.0 using javascript « Try Catch Consulting Weblog
20|Aug|2008 2[...] found this code while searching google. It is from Mitch Milam's blog and the entry is for CRM 3.0 SDK: Phone number format example bug fix. Thanks [...]
Leave a reply