0

I am trying to format a telephone number field in CRM 2011, but only if the field contains 10 digits. Some of the numbers have extensions, but I want to ignore those for now. I hacked existing code the best I could, but w/ my extremely limited knowledge of JS I will need some assistance. Any help is appreciated. Below is what I have so far..

    var phone = Xrm.Page.data.entity.attributes.get("telephone1");

    if(phone.length == 10)
    {
        phone.setValue( "(" + phone.substr(0, 3) + ") " + phone.substr(3, 3) + "-" + phone.substr(6, 4));
    }
Guido Preite
  • 14,905
  • 4
  • 36
  • 65
user2376230
  • 33
  • 1
  • 6
  • Possible duplicate of [Formatting the phone number](http://stackoverflow.com/questions/9973955/formatting-the-phone-number). You also have [Phone number format javascript](http://stackoverflow.com/questions/11519699/phone-number-format-javascript). – jww Sep 25 '14 at 00:01
  • What goes wrong with the [code you attempted](http://jsfiddle.net/96pj509r/1/)? – showdev Sep 25 '14 at 00:04
  • Hi showdev - there are no errors that come up, it just doesn't format at all. – user2376230 Sep 25 '14 at 00:22
  • Your code seems to format the number correctly in my [test fiddle](http://jsfiddle.net/96pj509r/1/). Maybe something different is going wrong with yours? – showdev Sep 25 '14 at 00:27
  • Put `console.log('Phone #: ', phone);` between the `var` and `if` lines and watch the console to see what you get. If you don't get anything, there's your problem. – Jared Farrish Sep 25 '14 at 00:35
  • CRM gets the value of "telephone1" in an alert statement, but only when there's no "if" statement .. once I add that "if" back in, it fails when I replace the setvalue line to an alert of it's value. I am doubting my code ...Is that definitely the right syntax on Line 3? ex: if(phone.length == 10) – user2376230 Sep 25 '14 at 01:42
  • 1
    the error is simple, you need to do a getValue() before checking the length. so the code will be: `var phone = Xrm.Page.getAttribute("telephone1").getValue(); if(phone != null && phone.length == 10) { Xrm.Page.getAttribute("telephone1").setValue( "(" + phone.substr(0, 3) + ") " + phone.substr(3, 3) + "-" + phone.substr(6, 4)); }` – Guido Preite Sep 25 '14 at 03:57
  • That's exactly it Guido. Thank you very much!! – user2376230 Sep 25 '14 at 07:27

2 Answers2

1

This might be an appropriate place for a little RegEx.

There are all sorts of edge cases in regards to phone numbers (invalid area codes and local exchanges, etc.), but this would work:

if(phone.match(/[0-9]{10}/))
{
    // do some stuff
}
LiquidPony
  • 2,188
  • 1
  • 17
  • 19
-1

How about trying to use an assignment statement like:

phone = ( "(" + phone.substr(0, 3) + ") " + phone.substr(3, 3) + "-" + phone.substr(6, 4));

instead of the phone.setValue();

3abqari
  • 228
  • 1
  • 2
  • 10