Format Phone number

Jeffce
Tera Expert

I am using a string field for users to enter phone number and or pull phone number from a source, is there a script available or has anyone used a script to format in this Fashion (###) ###-#### or ###.##.####

Thanks JJ

4 REPLIES 4

edwin_munoz
Mega Guru

Hello Jeffce,



Checkout this jsfiddle. Maybe it can help you.



http://jsfiddle.net/kaleb/Dm4Jv/



Thanks.


randrews
Tera Guru

i have not formatted it for them what i have done is validate it is in the correct format...




in any catalog item you can drop this in an onchange script and it should work.. just change the field to the phone number field...it should work on a regular form also as long as sho/clear field messages work... you shouldn't have to modify the script itself as it gets the field being changed itself.





On change script


function onChange(control, oldValue, newValue, isLoading) {


    if (isLoading || newValue == '') {


          return;


    }



    //checks the variable the onchange is for to verify it is a valid phone number


          var phone_field = control.id;


          g_form.hideFieldMsg(phone_field);


          var intNum = g_form.getValue(phone_field);



          if (!isPhoneDash(intNum))


          {


g_form.showFieldMsg(phone_field,'Invalid Phone Number Value ###-###-####','error');


          }


   


}


joshua_bice
Giga Expert

var numCheck = /^\(?[( ]?([0-9]{3})\)?[) ]?[. ]?([0-9]{3})[-.]?([0-9]{4})$/


if(!variable.match(numCheck)){


  //Probably an alert or something with variable = '';


}

I hope this works alright...I haven't done regex in a while, so I might be slightly off.


billi_lumley
ServiceNow Employee
ServiceNow Employee

function onChange(control, oldValue, newValue, isLoading) {


      if (isLoading || newValue == '') {


              return;


      }


      // Allows formats of (999) 999-9999, 999-999-9999, and 9999999999


      var pattern = /^[(]?(\d{3})[)]?[-|\s]?(\d{3})[-|\s]?(\d{4})$/;


      if(!pattern.test(newValue)){


              alert('Please enter a valid phone number in one of the following formats (999) 999-9999, 999-999-9999');


              g_form.setValue('phone', '');


      }


}