How to handle validation on phone number with country code ?

Snehal13
Kilo Sage

I have a SN catalog form that has a phone number field. The validation must ensure the below -

 

  1. Phone number must start with  plus sign (+)
  2. There must be a space after the country code

Example: For Australia, format should be: +61 458690289, For India, +91 7620243813

 

How to achieve this kind of functionality on client script validation, so that the moment phone number field is typed in and user moves to next field, it shows either a error or success message on the catalog form

1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron
Tera Patron

@Snehal13 

try this in onChange catalog client script on that variable

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

    // Clear previous messages
    g_form.hideFieldMsg('phone_number', true);

    // Allow empty if the field is optional
    if (!newValue) {
        return;
    }

    // +<countrycode><space><number>
    var phonePattern = /^\+\d{1,3}\s\d{6,14}$/;

    if (!phonePattern.test(newValue)) {
        g_form.showFieldMsg(
            'phone_number',
            'Phone must be in format +<country code> <number>, e.g. +61 458690289 or +91 7620243813.',
            'error',
            true
        );
    }
}

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

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

View solution in original post

2 REPLIES 2

Ankur Bawiskar
Tera Patron
Tera Patron

@Snehal13 

try this in onChange catalog client script on that variable

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

    // Clear previous messages
    g_form.hideFieldMsg('phone_number', true);

    // Allow empty if the field is optional
    if (!newValue) {
        return;
    }

    // +<countrycode><space><number>
    var phonePattern = /^\+\d{1,3}\s\d{6,14}$/;

    if (!phonePattern.test(newValue)) {
        g_form.showFieldMsg(
            'phone_number',
            'Phone must be in format +<country code> <number>, e.g. +61 458690289 or +91 7620243813.',
            'error',
            true
        );
    }
}

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

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