servicenow

umar5
Tera Contributor

............................................

6 REPLIES 6

@umar5 

something like this will work, please enhance as per your requirement

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue === '') {
        return;
    }

    // Check if the new value is already in the US format (123-456-7890)
    var usFormatRegex = /^\d{3}-\d{3}-\d{4}$/;
    if (usFormatRegex.test(newValue)) {
        return;
    }

    // Remove any non-numeric characters
    var cleaned = newValue.replace(/\D/g, '');

    // Check if the cleaned number has 10 digits
    if (cleaned.length === 10) {
        // Format the number as 123-456-7890
        var formattedNumber = cleaned.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
        g_form.setValue('mobile_number', formattedNumber);
    } else {
        // Optionally, you can add an alert or error message if the number is not valid
        g_form.addErrorMessage('Please enter a valid 10-digit mobile number.');
    }
}

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Ravi Gaurav
Giga Sage
Giga Sage

Hello ..
I have written and tested the script 

function convertToUSFormat(indianNumber) {
    var cleanedNumber = indianNumber.replace(/\D/g, '');

    if (cleanedNumber.startsWith('91')) {
        cleanedNumber = cleanedNumber.slice(2);
    }

    if (cleanedNumber.length === 10) {
        // Format the number into the US format: +1 (XXX) XXX-XXXX
        var formattedNumber = '+1 (' + cleanedNumber.substring(0, 3) + ') ' +
                              cleanedNumber.substring(3, 6) + '-' +
                              cleanedNumber.substring(6, 10);
        return formattedNumber;
    } else {
        return 'Invalid Indian number format';
    }
}

var indianNumber = '+91-9876543210';
var usFormattedNumber = convertToUSFormat(indianNumber);
gs.info(usFormattedNumber);  // Output: +1 (987) 654-3210

Please check

RaviGaurav_0-1736762693700.png

 




--------------------------------------------------------------------------------------------------------------------------


If you found my response helpful, I would greatly appreciate it if you could mark it as "Accepted Solution" and "Helpful."
Your support not only benefits the community but also encourages me to continue assisting. Thank you so much!

Thanks and Regards
Ravi Gaurav | ServiceNow MVP 2025,2024 | ServiceNow Practice Lead | Solution Architect
CGI
M.Tech in Data Science & AI

ï”— YouTube: https://www.youtube.com/@learnservicenowwithravi
ï”— LinkedIn: https://www.linkedin.com/in/ravi-gaurav-a67542aa/