Skip to main content
Kinetic Community

Cleaning Data using Regular Expressions

Sometimes you may want data to be in a certain format, but you don't want to give the user a validation error (eg. about things like leading and trailing white spaces) or writing the validation string may be undesirable.  In these cases, you can use a javascript on submit or on change that corrects the data.


You may want to trim white spaces from a free text field.  That is covered in this article.  You may also want to sanitize data you are going to be using in functions or comparisons later on.  Say you've asked for a user id to be created in a new system.  No spaces are allowed and only letters, numbers, and . are valid entries.  You want to trim any leading or trailing spaces, and you want to take any spaces that aren't leading and trailing or any special characters and turn them into a period. The following example js can be called from an On Change event to clean the data in a way that is visible to the user, or you call this On Submit.


function fixEntry(text) {
       text = text.replace(/(\n|\t|\r)/g," ");//replaces a new line, tab, or return character with a space
       text = text.replace(/(^\s*)|(\s*$)/gi,"");  //removes trailing and leading white spaces
       text = text.replace(/[ ]{2,}/gi," ");  //changes multiple spaces into a single space 
       text = text.replace(/[^0-9a-zA-Z\.]/g,"."); //changes non-aphanumeric characters that aren't . to a .
       text = text.replace(/\.{2,}/gi," ");  //changes multiple . into a single .
       return text;