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.

Ravi Gaurav
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