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); } }