Using Regular Expression in Catalog Client Script to Limit Entry to 3 Digit All Numeric Entry

jmiskey
Kilo Sage

I am trying to verify that a Service Catalog field entry is restricted to exactly a three digit value (i.e. 051, 789, etc).  So I am trying to write a Catalog Client Script using Regular Expressions, but it is not working.  I keep getting an error message that says "There is a JavaScript error in your browser console" in the Service Portal when I enter an invalid entry in that field, like "AAAAA".

I tried two different methods, but neither one worked.  Here is the first:

find_real_file.png

Here is my second attempt, which is very similar to one we wrote for a Variable Set some time ago, but this one isn't working either.

find_real_file.png

Can anyone see what my issue is?

Thanks

1 ACCEPTED SOLUTION

jmiskey
Kilo Sage

Thanks for the attempts.  Playing around, we finally figured out something that works.  We used this code to restrict it to numbers only:

 

function onChange(control, oldValue, newValue, isLoading) {
	if (isLoading || newValue == '') {
		return;
	}
	var number = g_form.getValue('pbp_id');

	if(!number.match(/^\d{3}/)){  
		alert('Please enter only a 3 digit number');
		g_form.setValue('pbp_id','');  
	}

}

And then we used the following Variable Attributes to restrict the length,

max_length=3,min_length=3

View solution in original post

6 REPLIES 6

Rohit Kaintura
Mega Guru

You can do this by getting the length of that particular field and put restriction on basis of that.

 

Please mark my answer correct and helpful if my answer helped u. Thank you.

Pradeep Sharma
ServiceNow Employee
ServiceNow Employee

Hello,

 

Try with below script and let me know if this works.

 

function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
var val = g_form.getValue('pbp_id');
var regexp= new RegExp('^[0-9]{3}$');
var s = regexp.test(val);
if(s == 'false')
{
alert('Please enter exact 3 numbers only');
g_form.setValue('pbp_id','');
}


}

 

Thanks,

Pradeep Sharma

Unfortunately, that didn't seem to work.  It didn't return any errors, but it didn't seem to do anything either.

jmiskey
Kilo Sage

Thanks for the attempts.  Playing around, we finally figured out something that works.  We used this code to restrict it to numbers only:

 

function onChange(control, oldValue, newValue, isLoading) {
	if (isLoading || newValue == '') {
		return;
	}
	var number = g_form.getValue('pbp_id');

	if(!number.match(/^\d{3}/)){  
		alert('Please enter only a 3 digit number');
		g_form.setValue('pbp_id','');  
	}

}

And then we used the following Variable Attributes to restrict the length,

max_length=3,min_length=3