Format phone number field to 1 (111) 111-1111

dhazlettjr
Giga Contributor

I have created a client script to format a field and have the output of (111) 111-1111. The only problem I am facing is hardcoding a 1 in front of the number. Example, If a user inputs a 10 digit number, it should format to 1 (111) 111-1111. My code work fine, IU just cant get a 1 automatically added once the onChange script runs.  Any ideas?

 

 

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


if (isLoading || newValue === '') {
return;
}

g_form.hideFieldMsg('u_preferred_phone_number');
var pattern = /^\(\d{3}\)\s\d{3}-\d{4}$/;
var phone = g_form.getValue('u_preferred_phone_number');

if (!pattern.test(phone)) {
phone = phone.replace(/\D/g, '');
var regex = /^\d{10}$/;
var is_valid = regex.test(phone);
if (!is_valid) {
g_form.clearValue('u_preferred_phone_number');
g_form.showFieldMsg('u_preferred_phone_number', "Please enter 10 digits", 'error');

} else {
phone = '(' + phone.slice(0,3) + ') ' + phone.slice(3,6)+'-' + phone.slice(6,10);
g_form.setValue('u_preferred_phone_number', phone);
}
}
}

1 ACCEPTED SOLUTION

Abhishek Pidwa
Kilo Guru

Hello , 

 

So I tried your code in my personal instance and I believe you would just need the change in your script a bit (appending 1 and modifying the regex pattern). I have highlighted it Yellow:

 

find_real_file.png

 

This will work as intended:

 

find_real_file.png

 

Let me know if you have any questions. 

 

Please mark this answer as helpful/correct if this solves your problem.

View solution in original post

3 REPLIES 3

Abhishek Pidwa
Kilo Guru

Hello , 

 

So I tried your code in my personal instance and I believe you would just need the change in your script a bit (appending 1 and modifying the regex pattern). I have highlighted it Yellow:

 

find_real_file.png

 

This will work as intended:

 

find_real_file.png

 

Let me know if you have any questions. 

 

Please mark this answer as helpful/correct if this solves your problem.

WOW! Thank you very much.  I never thought of adding to the regex itself.  

Yup simple thought sometimes works. Can you mark this answer as correct and close the thread so that others can benefit from it.