Welcome Login
Blog Photos Links

RSS Feed

Remove invalid characters from a field in ServiceNow

July 1, 2013, 10:34 am - James Farrer

Over the weekend I helped with an issue that came up involving form validation in ServiceNow. I've seen this a few times so I thought I'd throw out a reminder to myself and others about it. The goal was to remove invalid characters from a field leaving only numbers. At first this seems pretty simple, just do a regex and set the new value.

It's really not much more complicated than that, but there is one more very important step to take. Since the code is running in an onChange client script if you just set the new value then it will cause the onChange to run again. This onChange will run even if the value hasn't changed.

The trick is to perform a simple check in the function for whether the updated string is different than the original and only updating the value if it has changed. In general this is a good practice that often gets overlooked.

Leaving it out will result in StackOverflow errors from an infinite loop of onChange calls.

Here's the client script code, just replace "your_variable_name" with your own and you should be on your way:

function onChange(control, oldValue, newValue, isLoading) {
    
    // remove invalid characters from field
    var clean_str = newValue.replace(/[^d]/g,'');
    
    if(newValue != clean_str){
        g_form.setValue('your_variable_name', clean_str);
    }
    
}

What's New

There are currently no new items, please check back later.

Archives
2021 (2)
  September (1)
  May (1)
2019 (1)
  August (1)
2018 (3)
  August (1)
  April (1)
  January (1)
2017 (1)
  January (1)
2016 (4)
  December (1)
  November (1)
  May (1)
  January (1)
2015 (1)
  December (1)
2014 (2)
  August (1)
  February (1)
2013 (4)
  October (1)
  July (1)
  June (1)
  April (1)
2012 (11)
  December (2)
  October (3)
  September (1)
  May (1)
  April (1)
  February (2)
  January (1)
2011 (14)
  December (1)
  November (1)
  September (2)
  July (2)
  June (1)
  May (1)
  April (2)
  March (3)
  January (1)
2009 (2)
  October (1)
  June (1)
2008 (1)
  September (1)