I often encounter backend codebases where data isn't validated before being processed or inserted directly into the database. This can cause serious bugs, as relying solely on your frontend buddy can lead to headaches, ruin the flow, result in unwanted and unexpected data in the database, and make you vulnerable to SQL injection if you are using an SQL database.
What's the solution then?
I agree that data validation is a must, but it isn't always easy to get right.
Here's what you can do:
Don't trust anyone.
Validating data involves four crucial steps:
- Check the type.
- Validate the format.
- Refine it.
- Transform it (optional).
We often stop at the first step and ignore the rest. Don't do that. Take a simple example of validating a phone number. You accept a "string" and check if it is a string. If so, you allow it and let it go to the database. No errors for now. But what if you have to verify that phone number with some third-party API and the format of the phone number isn't valid? Handling it later may still be possible, but it's not a good user experience to show the user that they have input the wrong data because we didn't validate the format earlier. Now they have to provide it again in the proper format.
To create a good user experience, you should always:
- Check the data type (string, boolean, integer, object).
- Validate the format - if it's a phone number, it must look like one.
- Refine it - make it perfect for future use cases. For example, if you don't need the "+" at the start, remove it now.
- Transform it - after removing the "+", you may be left with an alphanumeric string, but you need a number instead of a string, so transform it.
That's all you need to take care of to make your backend more robust.
If you are a TypeScript lover like me, you can consider using Zod to fulfill all of the above criteria. It's a comprehensive library with great TypeScript support.
Thanks for reading.
Top comments (0)