Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Make Catalog Client Script Only Allow Positive Numbers

jmiskey
Kilo Sage

We have a Catalog Client Script that we are applying to the OnChange event of a Single Line Text variable.  We only want to allow numeric entries (it is a price field).  The script sucessfully only allows numeric entries.  The code looks like this:

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

	var integer = /^[0-9.,]*$/;

	if(!integer.test(newValue)) 
	{
		alert('Please enter a valid number.');
		g_form.clearValue('settlement_amount');
	}

}

We would like to enhance this a little to only allow positive entries (entries greater than zero). 

How can we amend this code to do that?

Thanks.

1 ACCEPTED SOLUTION

jmiskey
Kilo Sage

OK, I was overthinking things.  The first clause already does not allow negative entries.  So all you really have to do is add a second IF clause to check for a second condition to see if the value entered is zero. 

So, my amended code looks like this:

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

	//make sure they only enter numbers, comma, decimal, or dollar sign
	var integer = /^[0-9.,]*$/;

	if(!integer.test(newValue)) 
	{
		alert('Please enter a valid number.');
		g_form.clearValue('settlement_amount');
	}

	//make sure they do not enter just zero
	if(newValue == 0) 
	{
		alert('Please enter a non-zero value.');
		g_form.clearValue('settlement_amount');
	}
}

This works great, as it allows any positive number greater than zero, including decimals, and allows commas in the numeric entries.

View solution in original post

6 REPLIES 6

sachin_namjoshi
Kilo Patron
Kilo Patron

use below regex for allowing only positive numbers

 

^(\d|,)*\d*$

 

Regards,

Sachin

Where exactly do I place that in the code above?

 

Hi ,



 Your code should be like this:

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

if (isLoading || newValue == '') {
return;
}

var integer = /^[1-9][0-9]*$/ ;

if(!integer.test(newValue))

{

alert('Please enter a valid number.');

g_form.clearValue('settlement_amount');

}
}

 

Please mark it as helpful (or) correct if it helps.

 

Thanks,

Sumanth

I am sorry, but the Regex code I am currently using I did not come up with myself, I am borrowing it from elsewhere.  I am not really any good with Regex code.

No matter how I try to put your Regex code in my Script, I come up with scripting errors.  I cannot get your code to work at all.  

Are you able to get it to work?