Script to limit max size of string field.

Ian46
Tera Contributor

Hi,

I have many string fields set to 400 characters. This allows the boxes to be the right size. However I need to stop users putting in too much data. How best to do this with a script?

I tried an On Change Client script, but it didn't work:

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
   if (isLoading || newValue === '') 
   {
      return;
   }
   if(newValue.length>4000) 
   {
      g_form.showErrorBox("your_field","You cannot enter more than 4000 characters",true);
   }
}

 

Can anyone suggest the best way to achieve this?

Thanks Ian

14 REPLIES 14

Hi,

it should work

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
   if (isLoading || newValue === '')
   {
      return;
   }
   if(newValue.toString().length > 4000)
   {
     alert('You are not allowed beyond 4000');
   }
}

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Thanks that has worked, although the user can get round it by ignoring the error message. How would it be possible to stop them saving the form altogether?

you can use onSubmit client script 

add below code in onSubmit client script. 

 if(g_form.getValue('fieldname').length > 4000)
   {
     alert('You are not allowed beyond 4000');
return false;
   }

 

Note: add field name which you want to check , g_form.getValue('Your Field')

Thanks I think this will work perfect. I have multiple fields to limit. Can I use a comma and add additional field names? e.g. (fieldname1, Fieldname2'.length > 4000)  ? I am conscious that I don't want to have 20 odd scripts all running on the same form at one time.

 

Thanks

 

You should use Client script, Glide Ajax for this.

Glide Script script include should refer system property. This system property can be used to provide list of fields which needs max length validation.

 

This way in future you just update system property value so that you don't have to update code.

 

Regards,

Sachin