Max Length on Large String Fields in ServiceNow

///Max Length on Large String Fields in ServiceNow

Max Length on Large String Fields in ServiceNow

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);
    }
}
By | 2018-07-09T15:01:31+00:00 January 7th, 2010|Categories: Client scripts|Tags: , |13 Comments

About the Author:

Mark has worked in the IT industry since 2002 and with ServiceNow since 2007. He is the founder and creator of SN | Guru and the co-founder of Crossfuze, one of the worlds leading ServiceNow consulting partners. Prior to co-founding Crossfuze, he worked for ServiceNow as a Senior Architect on the Professional Services team. He has personally led dozens of successful implementations encompassing every part of the ServiceNow platform. He is also responsible for designing and developing groundbreaking ServiceNow solutions and best practices in the form of various applications, turnkey solutions, and integrations during his tenure at ServiceNow, Crossfuze and, of course, SN | Guru. These solutions are used today by ServiceNow administrators and consultants alike in hundreds of ServiceNow instances around the world!

13 Comments

  1. John Chapin January 8, 2010 at 1:19 am - Reply

    You rock — this is great. Thanks for this stuff!

  2. Scott Hetzel June 16, 2010 at 7:58 am - Reply

    Could you require a minimum number of characters to be typed in a text box? I’ve searched but have not found an answer yet…

    Thanks,

    Scott

    • Anonymous June 16, 2010 at 11:09 am - Reply

      You can. That would probably best be accomplished by using an ‘onSubmit’ client script on the table of your choice. This script sample should help.

      function onSubmit() {
         //Require at least 10 characters in the 'Comments' field
         var mLength = 10;
         var control = g_form.getControl('comments');
         if(control.value.length < mLength){
            g_form.hideErrorBox('comments');
            g_form.showErrorBox('comments', 'You must type at least ' + mLength + ' characters in this field.');
            return false;
         }
         else{
            g_form.hideErrorBox('comments');
         }
      }
  3. Priyanka June 20, 2011 at 5:23 pm - Reply

    Hi Mark,

    I am trying to reduce the width for a string in dictionary entry from 1000 to 200. But I am not able to..I tried disabling business rule “Dictionary Change Rationally” which prevents making string length shorter. But this too is not working.

    Let me know if there is any way to do it.

    • Mark Stanger June 20, 2011 at 11:42 pm - Reply

      That should be all you need to do. I just tested on the ServiceNow demo instance and it worked without issue. You should confirm that it works for you there and then open a ticket with support if you still can’t get it to work in your own instance.

  4. Priyanka June 21, 2011 at 4:54 pm - Reply

    Hi Mark,

    Thanks for the info.

    I tried in ServiceNow demo and it works fine.. but its still not working in my instance.. 🙁

  5. Derrick J Wippler August 9, 2011 at 1:56 pm - Reply

    Here is a slightly more re-useable form.

    function onLoad() {
       g_form.getControl('u_public_comments').onkeyup = function() { isMaxLength( 1000, 'u_public_comments' ) };
       g_form.getControl('description').onkeyup = function() { isMaxLength( 1000, 'description' ) };
    }

    function isMaxLength( length, control ){
       var control = g_form.getControl(control);
       if (control.value.length > length){
          g_form.hideErrorBox(control);
          g_form.showErrorBox(control, 'You have reached the maximum character limit for this field.');
          control.value=control.value.substring(0,length);
       }
       else{
          g_form.hideErrorBox(control);
       }
    }
  6. Louwee G October 4, 2011 at 5:13 pm - Reply

    hi, this script was very useful, but i am having a hard time applying the same script on a different field on the same form.

    I am trying to use this same script on 4 different fields on the same form, i have attempted to modify the script for the 2nd field but it cancels out the 1st script on the 1st field.

    Field names are u_header1, u_header2.

    thanks in advance.

    • Mark Stanger October 4, 2011 at 10:14 pm - Reply

      I haven’t ever tried it with 2 fields on the same form but I think if you’re having issues it’s because you’ve to 2 counters with the same DOM ID. You’ll need to change the following lines so that they are unique for each counter you use…

      counter.id=’counter’;

      var countControl = gel(‘counter’);

      You’ll also need to change every place in the script that references ‘comments’ to be the name of your field.

  7. Hema August 21, 2014 at 3:24 am - Reply

    Hi Mark,

    I have a multi line text field which is hidden in the catalog form and visible in the requested item page. I have text (whose length is exceeding 4000 characters) getting stored in this multi line text during On Submit and hence i see only truncated data on the requested item form. Is there any way to increase the size of the multi line text field such that how much ever text is stored during submit is visible on the requested item?

    Thanks a lot in advance,
    Hema.

    • Mark Stanger August 21, 2014 at 6:32 am - Reply

      I don’t know of any way that you can temporarily increase the size, you have to have it large enough to store any data. I’ve never heard of the problem you describe though so I’d guess you’re using a different database config than the standard ServiceNow setup. The only thing I can suggest is to output the value of that field in your onSubmit script and then again in a business rule before and after update to the table to see where the value is getting lost. Then you’ll know where you need to increase the field length.

  8. Majid Raqba March 6, 2017 at 9:02 am - Reply

    I am new in servicenow working on ssr . thanks a lot. u are the king

Leave A Comment