Let's say you're building an API for user registration. A user sends data and you save it to the database — sounds simple, right? But what if the user sends weird characters instead of a name? Or forgets to provide the required email field? Or the age turns out to be negative? All of that can lead to bugs, broken app logic, or worse — security vulnerabilities.
Validation is the process of checking that the data coming into your app is correct. It makes sure the data meets the criteria you expect: complete, valid, and safe.
Without validation:
- Your data in the database can be "dirty" (incorrect or incomplete).
- Your app logic can behave incorrectly.
- Your app can become a target for attacks (e.g., SQL injections or XSS).
Problems validation solves
- Bad user input:
- Fields remain empty when they're required.
- Invalid formats are entered (for example, "123abc" in an email field).
- Protection from attacks:
- Protection against malicious input, like SQL injection.
- Keeping business rules:
- For example, an event end date can't be before its start date.
- Improved data quality:
- The better your validation, the fewer headaches you'll have processing data later.
Main types of validation
1. Client-side validation
Client-side validation runs on the client (for example, in the browser via JavaScript). It helps catch errors almost instantly, before the request even reaches the server.
Example of client-side validation:
<form>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>
When a user tries to enter text that doesn't match the email format, the browser will automatically show an error message.
Problem: client-side validation is easy to bypass (for example, using tools to send raw HTTP requests), so you can't rely on it alone.
2. Server-side validation
Server-side validation happens on the server after receiving data from the client. It's mandatory, since the server must protect itself from invalid and malicious data regardless of the client.
Example of server-side validation (in Java):
public String validateEmail(String email) {
if (email == null || !email.contains("@")) {
throw new IllegalArgumentException("Invalid email format");
}
return email;
}
3. Business validation
This kind of validation enforces the business rules specific to your app. For example:
- An employee can't be assigned to a project if they don't have the required qualification.
- A discount on a product can't be more than 50% if the product is in the "new" category.
Example:
if (discount > 50 && productCategory.equals("new")) {
throw new BusinessRuleViolationException("Discount for new products cannot exceed 50%");
}
Tools and libraries for validation
Bean Validation API
In the Java world there's a standard for data validation — Bean Validation API (JSR 380). It's a powerful and flexible library that lets you validate data using annotations.
Example of using Bean Validation
Let's say we have a class User, and we want to validate its fields:
import javax.validation.constraints.*;
public class User {
@NotNull(message = "Name must not be empty")
private String name;
@Email(message = "Invalid email format")
private String email;
@Min(value = 18, message = "Age can't be less than 18")
private int age;
// Getters and setters...
}
How it works:
- The
@NotNullannotation checks that the field isn't null. @Emailchecks that the string matches an email format.@Minensures the age won't be less than 18.
If you try to persist an invalid object or pass it to a service, a javax.validation.ConstraintViolationException will be thrown, which you can handle in your app.
Real-world examples
1. User registration
When you register a user, you can't just accept any data. Here's how different types of validation are used:
- Client-side validation: check email and password formats with regexes.
- Server-side validation: check that the email is unique.
- Business validation: for example, users under 18 can't register.
2. Online shop
In the checkout flow:
- Client-side validation: make sure all required fields are filled out.
- Server-side validation: verify the provided payment card is valid (via an API).
- Business validation: ensure the order can't be placed if the selected product is no longer available.
Wrap-up
Implementing validation at all levels (client, server, business logic) isn't just good practice — it's necessary. For example, if you only rely on client-side validation, any script-kiddie can send requests directly and bypass checks. If you ignore business validation, you risk breaking rules and app logic, which can lead not only to bugs but also to financial loss.
Next we'll dive into using the Bean Validation API and annotations like @NotNull, @Min, @Max, @Size, and others. Then we'll learn how to wire them into our controllers and REST APIs. Get ready — it's just getting started!
GO TO FULL VERSION