Validating user input is crucial to ensure data integrity and application security. Laravel 12 offers a robust set of validation rules that simplify this process. Whether you're a beginner or an experienced developer, understanding these rules can significantly enhance your application's reliability.
In this article, we'll explore the top 10 Laravel 12 validation rules with practical examples to help you implement them effectively.
Ensures that the field is present and not empty.
$request->validate([
'name' => 'required',
]);
Validates that the field contains a valid email address.
$request->validate([
'email' => 'required|email',
]);
Sets minimum and maximum character lengths for strings or numeric ranges.
$request->validate([
'password' => 'required|min:8|max:20',
]);
Checks that two fields match, commonly used for password confirmation.
$request->validate([
'password' => 'required|confirmed',
]);
Ensures the value is unique in a specified database table.
$request->validate([
'email' => 'required|email|unique:users,email',
]);
Validates the field against a regular expression.
$request->validate([
'username' => ['required', 'regex:/^[a-zA-Z0-9_]{5,}$/'],
]);
Validates that the field's value is (or isn't) within a given set.
$request->validate([
'role' => 'required|in:admin,user,editor',
]);
Validates that the field is a valid date and matches a specified format.
$request->validate([
'birthdate' => 'required|date|date_format:Y-m-d',
]);
Allows the field to be null, but if present, it must pass validation.
$request->validate([
'middle_name' => 'nullable|string|max:50',
]);
For complex scenarios, you can create custom validation rules.
use App\Rules\Uppercase;
$request->validate([
'title' => ['required', new Uppercase],
]);
You might also like: