Welcome! As you start building APIs, one of the most important things you will learn is how to protect your application from bad or unexpected data. This is called data validation.
Imagine you are building a user registration form. If someone sends an empty name
, a fake email
, or even tries to send code instead of text, your application could break or behave in ways you do not expect. In the real world, this can lead to bugs, security issues, or even data loss.
By validating incoming data, you ensure that your API only accepts information that is correct and safe. This is a key step in building robust and reliable APIs.
Before we dive into validation, let’s quickly review the basic setup you will be working with. Here is a simplified version of our API and user data structure:
This code defines a simple User
type and a list of users
. Our API will allow clients to add, update, and remove users. Now, let’s see how we can make sure the data sent to our API is valid.
Data validation means checking that the information sent to your API is what you expect. This usually involves:
- Making sure required fields are present (like
name
andemail
) - Checking that each field is the correct type (for example,
name
should be a string) - Making sure values are allowed (for example,
role
can only be'user'
or'admin'
) - Ensuring optional fields, if provided, are valid (like
isActive
being a boolean)
If you skip validation, your API might accept data that causes errors or security problems later.
⚠️ The examples we’ve shown here are simple starting points. They’re meant to demonstrate how validation works — but in real-world applications, you’ll often want stronger and more precise rules. For example, instead of just checking if an email includes '@', you might:
- Use a regular expression (regex) to ensure the email format is valid
- Add length limits to fields like
name
(e.g., 2–50 characters)- Prevent users from sending unexpected fields like
"superAdmin": true
- Require that optional fields like
isActive
, if included, are actually booleans, not"true"
strings
Let’s build a function that checks if the incoming user data is valid. Here is the code for validateUserPayload
:
Let’s break down what this function does:
- It starts by creating an empty list called
errors
. - It checks if the
payload
is an object. If not, it returns an error right away. - It checks if
name
is a non-empty string. If not, it adds an error message. - It checks if
email
is a string and contains an@
symbol. If not, it adds an error message. - If
role
is provided, it must be either'user'
or'admin'
. Otherwise, it adds an error. - If
isActive
is provided, it must be a boolean (true
or ). Otherwise, it adds an error.
Now that you’ve seen a simple validation function, let’s look at how we can improve it. Real APIs must account for edge cases, malformed input, and even attempts to sneak in unwanted fields.
Here’s an improved version of the validateUserPayload
function that includes:
- Field whitelisting (to block unexpected fields)
- Better email validation using a regular expression
- Minimum and maximum name length
- Separate function for partial validation (used in PATCH)
- This ensures that fields like
passwordResetToken
,adminBypass
, or__proto__
cannot sneak in. Only the expected keys are accepted. - Instead of checking only for
'@'
, this uses a regular expression to confirm the format is valid.
Now, let’s see how to use this validation function in your API routes. Here is how it works in the POST
route for users:
What’s happening here?
- The API tries to read the incoming data as JSON.
- It calls
validateUserPayload
to check the data. - If there are any errors, it returns them to the client with a
400 Bad Request
status. - If the data is valid, it creates a new user and adds it to the list.
🔐 This structure also helps protect your server from accidental or malicious misuse. Without validation, users could send in a
role: 'superadmin'
,isActive: 'yes'
, or even unexpected fields likepasswordResetToken
— and your app might silently accept them. This same pattern is used in thePUT
route to update users. By using the validation function, you ensure only good data is accepted.
Example response for invalid data:
In this lesson, you learned why data validation is important and how to add it to your API. You saw how to build a validation function that checks for required fields, correct types, and allowed values. You also learned how to use this function in your API routes to return helpful error messages when the data is not valid.
Now you are ready to practice these skills. In the next exercises, you will get hands-on experience writing and using validation functions to make your APIs more robust and secure. Good luck, and remember: always validate your data!
