Validate tracking in a string field with Comma Separated Values

Jimmy45
Giga Guru

I have a string field (tracking_numbers)

In this string field we are allowing our technicians to put in 12 digit tracking numbers separated by a comma and space:

 

Example: 123456789321, 444555666777, 877755447733

 

3 tracking numbers.

 

How do I create a RegExp that will validate that each of these tracking numbers are:

  • only numbers
  • each are 12 digits long?

I created an onChange client script, but it doesn't seem to be working.  Any help would be most appreciated.  I also noticed I keep getting an unterminated string constant error.  Not sure what to do here.

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    var regexp = /^[0-9]{12}*(,)?[0-9]{12}*$/; // Check that they are 12 digits and numeric
	var str = newValue.trim(); // trim leading and ending spaces
    if (!regexp.test(str)) {
		g_form.clearValue('tracking_numbers');
		g_form.showFieldMsg('tracking_numbers', 'Tracking numbers should be numeric entry only and be 12 digits each', 'error');
    } else if (str != newValue) {  // if there was leading or ending spaces, set the value to trimmed value
		g_form.setValue('tracking_numbers', str);
	}
}

 

1 ACCEPTED SOLUTION

Allen Andreas
Administrator
Administrator

Hi,

You can try using this as your regexp:

 

/^[0-9]{12}(,[0-9]{12})*$/

I'm unsure if your trim is causing any issues and ServiceNow should possibly remove those spaces, so you may not need that? Try without first, etc.

 


Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!

View solution in original post

5 REPLIES 5

Allen Andreas
Administrator
Administrator

Hi,

You can try using this as your regexp:

 

/^[0-9]{12}(,[0-9]{12})*$/

I'm unsure if your trim is causing any issues and ServiceNow should possibly remove those spaces, so you may not need that? Try without first, etc.

 


Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!

Thanks Allen!
I replaced the regexp and am still getting the Parsing error:  Unterminated regular expression

 

is this correct in ServiceNow?

Jimmy45_0-1680099629219.png

 

Hello @Jimmy45 

When I pasted your original script, yes, I saw the error.

When I pasted in my suggested line, the error went away:

AllenAndreas_0-1680100997914.png

Please try again.


Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!

Community Alums
Not applicable

Hi,

the problem is you regex, which is not correct. The correct version was posted by Allen Andreas. You should still keep your trim function in place though, since SN will not automatically trim the value and spaces will cause the regex to not match.

If my answer helped, please mark it as helpful, thank you!