How to make a variable in catalog form to accept numeric numbers only?

AKASH BANERJEE
Mega Guru

Hi All,

 

I am using the below code to make a variable accept only numeric value but it it not working.

Please check and suggest how we can make a field accept numeric values only.

 

function onChange(control, oldValue, newValue, isLoading) {


if (isLoading || newValue == '') {


return;


}


var regexp = /^[+]?\d*$/;


if(!regexp.test(newValue)) {


alert('Please enter numeric value');


g_form.setValue('provide_approximate_yearly_spend','');


}

}

1 ACCEPTED SOLUTION

Musab Rasheed
Tera Sage
Tera Sage

Hello,

No need for client script, you can use Regex method, please go through articles

https://www.servicenow.com/community/developer-articles/field-validation-regular-expressions/ta-p/23...

https://www.servicenow.com/community/developer-articles/common-regular-expressions-and-cheat-sheet/t...

Please hit like and mark my response as correct if that helps
Regards,
Musab

View solution in original post

3 REPLIES 3

Musab Rasheed
Tera Sage
Tera Sage

Hello,

No need for client script, you can use Regex method, please go through articles

https://www.servicenow.com/community/developer-articles/field-validation-regular-expressions/ta-p/23...

https://www.servicenow.com/community/developer-articles/common-regular-expressions-and-cheat-sheet/t...

Please hit like and mark my response as correct if that helps
Regards,
Musab

Ahmmed Ali
Mega Sage

Hello @AKASH BANERJEE 

 

No need to write code as OOTB ServiceNow has regex defined for numeric value. Open your variable definition, go to "Type Specification" section in the form and select validation regex to number. Example:

 

AhmmedAli_0-1666698393742.png

 

Thank you,

Ali

If I could help you with your Query then, please hit the Thumb Icon and mark my answer as Correct!!

Thank you,
Ali

Sohail Ahmed
Tera Guru

Hi @AKASH BANERJEE ,

 

You can use validation regex from variable , or you can write a client script for the variable .

 

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


var phonenumber = g_form.getValue('phone_number'); // enter your variable name
if (isNaN(phonenumber)) { //isNAN Checks whether the entered value is number or not, isNAN = Not A Number

g_form.clearValue('phone_number');
g_form.showFieldMsg('phone_number', 'Only numbers are allowed in the phone number field, please use no spaces or any other characters when adding phone number', 'error');

}
}

 

Thanks,

Sohail