Welcome to Community Week 2025! Join us to learn, connect, and be recognized as we celebrate the spirit of Community and the power of AI. Get the details  

How to validate that the mobile number is 10 digits

ServiceNow Use6
Tera Guru

Hello,

I made a requirement in my mind.

The mobile number field is to be validated to be 10 digits long, if yes, the mobile number should be populated to the alternate mobile number field. Can you give me some insights into how to do it?

 

As of now I have created a variable x

var x = /d{10}

Now I need to validate the length of x should be 10. Not sure how to. 

 

P.S. Please don't give me the solution

1 ACCEPTED SOLUTION

Akshay Bhaskar
Kilo Sage

Hi, 

Please let me know if the below code works for you. It evaluates the user-entered phone number against a pre-set regular expression and sets the value of the alternate phone number field if the condition returns as true. I hope this helps you. 

var number = g_form.getValue('field_name');
var check = /^[0-9]{10}/;

var result = number.match(check);
if(result==true)
{ g_form.setValue('field_name', 'number'); }
else
{ alert("Dear Requestor, please make sure that the number you provide is 10 digits long"); }

View solution in original post

3 REPLIES 3

Feddy
Kilo Sage

You can try below script to validate , 10 digits phone number, 

function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
var pattern = /^[(]?(\d{3})[)]?[-|\s]?(\d{3})[-|\s]?(\d{4})$/;

if(!pattern.test(newValue)){
g_form.clearValue('<phone number backend value>');
g_form.showFieldMsg('<phone number backend value>', 'Please enter a valid Phone number', 'error');
};


}

Akshay Bhaskar
Kilo Sage

Hi, 

Please let me know if the below code works for you. It evaluates the user-entered phone number against a pre-set regular expression and sets the value of the alternate phone number field if the condition returns as true. I hope this helps you. 

var number = g_form.getValue('field_name');
var check = /^[0-9]{10}/;

var result = number.match(check);
if(result==true)
{ g_form.setValue('field_name', 'number'); }
else
{ alert("Dear Requestor, please make sure that the number you provide is 10 digits long"); }

Kalyani21
Mega Guru

Hello,

You can try something like this:

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

var oldV = oldValue;
var validRegExp = /^\(?(\d{3})\)?[ -]?(\d{3})[ -]?(\d{4})$/;
var checkPhone = g_form.getValue('phone_number_requested_for');

if (checkPhone.search(validRegExp) == -1)
{
alert('Enter valid mobile phone in : (999) 999-9999, 999-999-9999, and 9999999999 formats');
g_form.setValue('phone_number_requested_for',oldV);
}

}

 

Regards,

Kalyani Shaha