How to Format and Clean User Text

Sometimes you may want data to be in a certain format, but you don't want to give the user a validation error (for example, 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. 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.


    var text = K('field[Text to be Cleaned]').value();  //Set the variable 'text' to the value of the Field.
    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 .
    K('field[Text to be Cleaned]').value(text);  //Set the value of the Field to the 'Cleaned' value.