Best way to format a phone number 212-222-2222 | XM Community
Skip to main content

I am trying to format a text field phone number to show dashes and have found two ways. One using JS and the other using Matches Regex. I tried both examples and was not successful in my attempts. Can someone provide me direction on the best way to format a phone number so it will show the dashes in the field.

jQuery(".InputText").on("cut copy paste",function(e) {
e.preventDefault();
});
jQuery(".InputText").on('keypress',function(){
if(event.which != 8 && isNaN(String.fromCharCode(event.which))){
event.preventDefault(); //stop character from entering input
}
var s = this.value.replace(/-/g,'');
if(s.length==10){
event.preventDefault();
}
if(s.length!=0){
if(s.length>=3 && s.length<=5){
var s1 = s.slice(0,3);
var s2 =s.slice(3,s.length);
this.value=s1+"-"+s2;
}
if(s.length>=6){
var s1 = s.slice(0,3);
var s2 =s.slice(3,6);
var s3=s.slice(6,s.length);
this.value=s1+"-"+s2+"-"+s3;
}
}
and
REG.jpgI tried the above two options and they did not work for me.


Can you use a jQuery telephone input mask plugin instead of custom coding it?
Look at the jquery input mask: jquery-input-mask-phone-number - npm (npmjs.com)


When I try adding the above script to add dashes to format a phone number. I receive an error when I try to save. Please see image. I have been trying for some time to figure out how to add dashes to a phone number can you help me?
error.jpg


Leave a Reply