Phone number validation

User_267
Tera Contributor

In catalog form. There is a field call phone number.

User has to enter phone number in that field. And the phone number format is 123-456-7890.

If user doesn't enter in any above format. It shows error.

If user enters in above format . It needs to populate as (123)456-7890.

Require client script for this.

6 REPLIES 6

Amit Gujarathi
Giga Sage
Giga Sage

HI @User_267 ,
I turst you are doing great.
Please find the client script code for the same.

function onChangePhoneNumber() {
    var phoneNumberField = g_form.getValue('your_phone_number_field'); // Replace 'your_phone_number_field' with the actual field name

    // Regular expression to match the desired phone number format
    var phoneRegex = /^\d{3}-\d{3}-\d{4}$/;

    if (phoneRegex.test(phoneNumberField)) {
        // If the entered phone number matches the desired format, format it as (123)456-7890
        var formattedPhoneNumber = phoneNumberField.replace(/^(\d{3})-(\d{3})-(\d{4})$/, '($1)$2-$3');
        g_form.setValue('your_phone_number_field', formattedPhoneNumber); // Replace 'your_phone_number_field' with the actual field name
    } else {
        // If the entered phone number doesn't match the desired format, show an error message
        g_form.showFieldMsg('your_phone_number_field', 'Please enter phone number in the format 123-456-7890', 'error'); // Replace 'your_phone_number_field' with the actual field name
        g_form.clearValue('your_phone_number_field'); // Clear the field value
    }
}

// Attach the onChangePhoneNumber function to the onchange event of the phone number field
g_form.addOnChange('your_phone_number_field', onChangePhoneNumber); // Replace 'your_phone_number_field' with the actual field name

Was this answer helpful?


Please consider marking it correct or helpful.


Your feedback helps us improve!


Thank you!


Regards,


Amit Gujrathi



Peressildur
Tera Contributor

I had to deal with formatting phone numbers in a form once and getting it just right was trickier than expected. A simple client script can help with this. You could use a bit of JavaScript that listens for input in the field, checks if it matches the pattern 123-456-7890, and then reformats it to (123)456-7890 on the fly. It saves users from errors while still making sure the format stays consistent. It’s also handy to be aware that users might try using a temp mobile number from sites like Tardigrada, so keeping validation strict but not too overbearing helps maintain the quality of data without frustration.