The HTML 5 specification includes support for the ‘maxlength’ attribute for ‘TEXTAREA’ elements. This means that it’s much easier just to set that attribute rather than the massive script below unless you want a character counter to show the number of characters remaining. Unfortunately, Internet Explorer doesn’t support the ‘maxlength’ attribute until IE10 so the solution below still applies for the overwhelming majority of situations when you need to set a max length on a large string field in ServiceNow…at least until we see wider enterprise adoption of IE10+.

String fields typically aren’t anything to get too worked up over, but I’ve discovered a couple of cool tips on dealing with string fields in ServiceNow that might benefit somebody else at some point.

The first tip is to know what the difference is between a single-line text field and a multi-line text field in ServiceNow. It’s obvious when you look at them, but there are some details under the hood that you might not know about. The driver of these differences is the ‘Max Length’ value that you set on the dictionary entry for the string field. Any string field with a max length value less than or equal to 255 will be rendered as a single-line text field. As soon as you hit 256 or more characters for the max length, the field is changed to a multi-line text field.

DID YOU KNOW? The ‘Max Length’ value also has an effect on fields shorter in length than 255. If the max length is less than 80, the field will be rendered as a smaller text field on the form (similar to the ‘Number’ field on a task form). Anything 80 or greater is rendered as a wide, single-line text field (similar to the ‘Short description’ field on a task form).

The second tip is to understand what this does at the database level in a MySQL database. A field with a max length value less than or equal to 255 is designated as a ‘CHAR’ datatype in the database. The DB won’t accept a max length greater than what you specify for these fields.

As soon as your max length is 256 or more however, the field changes to a ‘VARCHAR’ datatype. The maximum length of one of these fields doesn’t have a direct correlation to the max length specified on the dictionary entry. There is a formula for where the max length ends for VARCHAR fields, but it’s typically so large that for all intents and purposes you can put as much information in one of these fields as you need.

The third tip is to understand what happens in the client-side interface for these fields. Any single-line field will be rendered as an ‘INPUT’ HTML element on the form. ‘INPUT’ elements have an attribute included called ‘maxlength’ that you can use to limit the number of characters that can be added to the field. ServiceNow uses the dictionary setting when it renders the HTML for these fields.

With a multi-line text field things work differently. These are rendered as a ‘TEXTAREA’ HTML element on the form. HTML doesn’t include a ‘maxlength’ attribute for these fields so you can input as many characters as you want into one of these fields. The only way to work around this HTML limitation is to set up a client script to limit the number of characters allowed.

Shown below are a couple of ‘onLoad’ client scripts that I’ve used before to force a maximum length for a multi-line text field in ServiceNow. Both are designed to work on the ‘comments’ field on any of the ‘Task’ tables.

The first is an example I came up with just for fun. It displays a counter text box that shows the number of characters left. It also changes the background color of the field at specified intervals. Probably a little bit overkill but it gives you a lot of possibilities. I actually had some sound effects with it at one point!


function onLoad() {
//Create the counter field and line break
var counterBreak=document.createElement('br');
var counter=document.createElement('input');
counter.id='counter';
counter.type='text';
counter.readOnly=true;
counter.size='4';
counter.maxlength='4';
counter.value='500';

//Create a text node to be a label for the counter
var counterLabel = document.createElement('text');
counterLabel.innerHTML=' characters left';

//Use the 'onkeyup' event to check the 'isMaxLength' function
//Get the control
var control = g_form.getControl('comments');
//Add the nodes to the form
var controlParent = control.parentNode;
controlParent.appendChild(counterBreak);
controlParent.appendChild(counter);
controlParent.appendChild(counterLabel);
//Set its onkeyup method
control.onkeyup = isMaxLength;
}

function isMaxLength() {
   var mLength=500;
   var control = g_form.getControl('comments');
   var countControl = gel('counter');
   if (control.value.length >= mLength){
      //If number of characters exceeds maxLength then trim the value
      control.value = control.value.substring(0, mLength);

      //Flash the label for the comments field red for 4 seconds and change field background color
      g_form.flash('new_call.comments', '#FF0000', -4);
      g_form.getControl('comments').style.backgroundColor='red';
   }
   // otherwise, update 'characters left' counter
   else{
      //Change the background color of the field depending on characters left
      if(control.value.length <= 200){
         g_form.getControl('comments').style.backgroundColor='';
      }
      if((control.value.length > 200) && (control.value.length <= 400)){
         g_form.getControl('comments').style.backgroundColor='yellow';
      }
      if(control.value.length > 400){
         g_form.getControl('comments').style.backgroundColor='orange';
      }
   }
   countControl.value = mLength - control.value.length;
}

Here’s a simplified example. It just shows an error message when the Max Length for the field is reached.


function onLoad() {
   //Use the 'onkeyup' event to check the 'isMaxLength' function
   //Get the control
   var control = g_form.getControl('comments');
   //Set its onkeyup method
   control.onkeyup = isMaxLength;
}

function isMaxLength(){
   var mLength=500;
   var control = g_form.getControl('comments');
   if (control.value.length > mLength){
      g_form.hideErrorBox('comments');
      g_form.showErrorBox('comments', 'You have reached the maximum character limit for this field.');
      control.value=control.value.substring(0,mLength);
   }
   else{
      g_form.hideErrorBox('comments');
   }
}

Putting it all together in a global UI script…

The above scripts work well enough if you’re just using this for a single field on a single form. It’s often better to create a global UI script that you can call if you’re going to use the function fairly often. The following script can be pasted directly into a UI script in your system. Once it’s in place, you can add a Max Length field check to any string field or catalog variable by using the following…

setMaxLength(‘[FIELD_OR_VAR_NAME]’, [MAX_LENGTH]);

function setMaxLength(fieldName, mLength){
    $(g_form.getControl(fieldName).id).observe('keyup', isMaxLength.bind(this, fieldName, mLength));
}

function isMaxLength(fieldName, mLength){
    var control = g_form.getControl(fieldName);
    if (control.value.length > mLength){
        g_form.hideErrorBox(fieldName);
        g_form.showErrorBox(fieldName, 'You have reached the maximum limit of ' + mLength + ' characters for this field.');
        control.value=control.value.substring(0,mLength);
    }
    else{
        g_form.hideErrorBox(fieldName);
    }
}