The importance of Trim()

Today we’ll focus on the importance of Trim() action in your code. As you know, Trim() will remove empty spaces from the beginning and end of any string of text.

Consider what we’ve discussed in our last article about validation. I’ve shown that you should always validate inputs before storing records in database. While you can validate in the frontend, the backend action and all actions in between, you must still validate in your Create/Update actions in the CS modules.

Now, consider that you develop the following form for the user to fill in the contact information:

As you can see, I’ve prefixed and suffixed my name with 5 space characters.

It’s obvious that we don’t want to store those space characters in database, that’s where Trim() shines.

Please note that various reasons exist for users to submit values containing spaces on the beginning or end of text strings such as:
– It’s difficult to see that a space character is there, specially if it’s only 1;
– Past values from other documents;
– Values that were imported from a spreadsheet or other source;

What should you do then?

First of all, you should enforce Trim() over all your string input fields in your client and server actions:

Client Action

Server Action

However, as we’ve already saw previously, your Create or Update actions should also enforce Trim() over all your text input fields:

As you can see, we ended by executing the same code in 3 different actions and you may argue this is redundant but:

SaveContact (Client Action): You should not miss this step, but if you do, this is would be the one that have less impact in the execution flow because it’s enforced by the server action.

SaveContact (Server Action): Like any other server action, you should always recheck client input as server actions are public endpoints that can be called directly.

Contact_CreateOrUpdate (CS Server Action): You can argue that if you already guarantee that SaveContact (Client and Server actions) already execute Trim(), this would be redundant. Please remember that Contact_CreateOrUpdate is a public action and this can be used in another context such as import from a Excel file.

Little details can make big difference
Tiago