Client script to restrict spaces - leading/trailing/intext

Brendan Hallida
Kilo Guru

Hi all,

I have a client script running on a variable that has the following requirements:

  1. trim leading and trailing whitespace
  2. change spaces in the text to _ (underscore)

 

var regex = new RegExp("^[a-zA-Z0-9_]*$");

var mailboxName = g_form.getValue('u_new_shared_mailbox_name');

if(!regex.test(newValue)){
 console.log('if statement working for ' + mailboxName);
//setting values
g_form.setValue('u_new_shared_mailbox_name', mailboxName.toString().replace(/\s/g, '_').trim());

The above works, except if I test with the leading / trailing whitespace only.  If I test with whitespace leading / trailing and a space between it all works perfectly.  Makes me think its an issue with the regex?

Does anyone have any ideas? Thanks in advance!

1 ACCEPTED SOLUTION

Hi Brendan,

I've changed the logic slightly, I'm now just checking if the email contains whitespace. Try the following in your client script:

var mailboxName = g_form.getValue('u_new_shared_mailbox_name'); //getValue returns string

	if(/\s/.test(mailboxName)){ //regex test for whitespace in mailbox name
		console.log('if statement working for ' + mailboxName);
		//setting values
		g_form.setValue('u_new_shared_mailbox_name', mailboxName.trim().replace(/\s/g, '_'));
	}

It works fine in my developer instance so let me know how you get along.

Brent

P.S. If my suggestion helped then please mark as helpful and/or correct so other community members can benefit from this information.

View solution in original post

6 REPLIES 6

No worries Brendan,

We just had a long weekend over in NZ too. Glad it is working for you.

Brent

IT IS NOT WORKING IN SERVICENOW PORTAL