Laravel validation is one of the best approaches to make sure that the incoming data via a form or inside controller action is valid and useable. By setting up the validation rules, you can make sure you have the right data that can be accessed. Another good factor? Developers won’t have to write long code, rather they can simply use Laravel validation rules and get started with it.
In this blog, we discuss the Laravel validation rules, what they are, and how you can implement them.
Why Laravel Validation Rules Are Important?
Laravel validation rules make sure that the collected data is correct, true, and trustworthy. It ensures data integrity and also Laravel security by making sure that the data collected is accurate and relevant – and free of any malicious attacks.
By implementing validation rules in Laravel, businesses get to save themselves from spending hefty costs as errors or missing information can lead to delays or data blunders.
In addition to that, it also helps with better decision-making and improves user experience.
We can take the example of ‘contact us form’ for Laravel form validation in which some fields are required, and user cannot continue their action without providing the correct information.
This is an example of data validation when an incoming request is made through a form.
What Are the Key Validation Rules in Laravel?
When building applications with Laravel, you have to make sure that the incoming data is correct and trustworthy. For this, there are different validation rules such as required, numeric, email, numeric, alpha, etc.
Below is a table of key validation rules in Laravel along with their description.
Validation Rule | Description |
---|---|
required | Ensures that the field is not empty. |
string | Validates that the field is a string. |
max:{value} | Ensures the field’s value does not exceed the specified length. |
min:{value} | Ensures the field’s value is at least the specified length. |
Validates that the field contains a valid email address. | |
unique:{table} | Ensures that the field’s value is unique in the specified database table. |
confirmed | Ensures that two fields (e.g., password and password confirmation) match. |
integer | Validates that the field is an integer. |
date | Validates that the field is a valid date. |
boolean | Validates that the field is either true or false. |
numeric | Ensures that the field contains a numeric value. |
regex:{pattern} | Ensures the field matches a specific regular expression pattern. |
url | Ensures the field contains a valid URL. |
array | Validates that the field is an array. |
in:{value} | Ensures the field’s value is within the specified set of values. |
exists:{table} | Ensures that the field’s value exists in a specific database table. |
timezone | Validates that the field contains a valid time zone. |
image | Validates that the field is an image file (e.g., .jpeg, .png, gif). |
file | Ensures the field contains a valid file. |
after:{date} | Ensures the field’s value is a date after a specific date. |
before:{date} | Ensures the field’s value is a date before a specific date. |
All of the validation rules have their own pros and cons but adding them to your Laravel web apps gives clean and authenticated data.
Types of Laravel Validation
In Laravel, you can set up form validation, email validation, password validation, and much more. As we have discussed form validation above with an example, let’s discuss email and password validation.
Email Validation
As the name suggests, this Laravel validator ensures that the input provided by the user as an email matches the given email format. The purpose of using email validation in Laravel is to help verify that a string submitted as part of a form or request meets the standard structure of an email address. Laravel provides a built-in email validation rule to achieve this. Below is an example of an email validator:
$request->validate([ 'email' => 'required|email', ]);
Below is the description:
- required: Ensures the field is not empty.
- email: Verifies that the input is a valid email address.
Advanced Email Validation: you can also apply advanced Laravel email validation that supports stricter email validation using the dns and spoof options:
>validate([ 'email' => 'required|email:rfc,dns', ]);
- rfc: Validates the email based on RFC 5321.
- dns: Checks the DNS records for the domain to verify its existence.
- spoof: Prevents email spoofing by verifying the domain.
Laravel Password Validation
Another form we have of Laravel validator is password validation. It is designed to ensure Laravel security by confirming that the entered passwords meet specific complexity and length requirements. Laravel provides a flexible Password class to define password rules. Below is an example:
Basic Password Validation:
$request->validate([ 'password' => 'required|min:8', ]);
- required: Ensures the password field is not empty.
- min:8: Specifies a minimum length of 8 characters.
Advanced Password Validation: Just like email validation, you can also leverage advanced password validation. For this, Laravel 8+ introduced the Password rule object for more robust password validation:
use Illuminate\Validation\Rules\Password; $request->validate([ 'password' => ['required', 'confirmed', Password::min(8)->letters()->numbers()->symbols()], ]);
Below is the description:
- Password::min(8): Specifies a minimum length.
- letters(): Requires at least one alphabetic character.
- numbers(): Requires at least one numeric character.
- symbols(): Requires at least one special character (e.g., !, @, #).
- confirmed: Ensures the password matches the password_confirmation field.
Customizing Validation Messages
Custom error messages for email or password validation can be defined in the messages method of a form request or in the lang/en/validation.php file.
Example:
'email' => 'The :attribute must be a valid email address.', 'password' => 'The :attribute must be at least 8 characters long and contain
Setting up Validation in Laravel
Before setting up other kinds of validation or generating requests, it is essential to set up the environment. Below is a detailed process of how to set up the environment seamlessly.
1. Set Up Your Laravel Application
The first step is to ensure Laravel is installed and running on your local environment or server. If you haven’t already installed Laravel, you can do so using Composer:
composer create-project laravel/laravel example-app
Verify the installation by starting the development server:
php artisan serve
Visit http://localhost:8000 to confirm the application is working.
2. Configure Your Database
If your form data will interact with a database (e.g., creating users), configure the database connection in the .env file:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=your_database_name DB_USERNAME=your_username DB_PASSWORD=your_password
Run migrations to create necessary database tables:
php artisan migrate
3. Create a Model (Optional)
If you’re saving form data to the database, create a model and migration for the relevant table. For example, to create a User model:
php artisan make:model User -m
This will generate:
- app/Models/User.php: The model file.
- database/migrations/xxxx_xx_xx_create_users_table.php: A migration file to define the database schema.
Define the table structure in the migration file and run:
php artisan migrate
4. Install and Configure Authentication (Optional)
If your form requires user authentication (e.g., registration or login forms), you can scaffold authentication quickly using Laravel Breeze or Laravel UI.
Example with Breeze:
composer require laravel/breeze --dev php artisan breeze:install npm install && npm run dev php artisan migrate
This will set up authentication routes, views, and controllers for handling user authentication.
5. Set Up the Form Routes
Define routes for the form submission. For example:
use App\Http\Controllers\UserController; Route::get('/form', [UserController::class, 'create'])->name('form.create'); Route::post('/form', [UserController::class, 'store'])->name('form.store');
The create method displays the form, and the store method handles form submission.
6. Create a Controller
Generate a controller to handle form-related logic:
php artisan make:controller UserController
In the controller, add methods for displaying the form and handling submission:
namespace App\Http\Controllers; use App\Http\Requests\MyFormRequest; class UserController extends Controller { public function create() { return view('form'); } public function store(MyFormRequest $request) { $validatedData = $request->validated(); // Process validated data, e.g., save to database return redirect()->route('form.create')->with('success', 'Form submitted successfully!'); } }
7. Prepare the View
Create a Blade template to display the form. For example, in resources/views/form.blade.php:
<form method="POST" action="{{ route('form.store') }}"> @csrf <div> <label for="name">Name:</label> <input type="text" name="name" id="name" value="{{ old('name') }}"> @error('name') <span>{{ $message }}</span> @enderror </div> <button type="submit">Submit</button> </form>
8. Generate a Form Request Class
Once the application is set up, create a Form Request class as described earlier:
php artisan make:request MyFormRequest
9. Set Up Middleware (Optional)
Ensure that CSRF protection and middleware are in place for secure form submissions. Laravel automatically applies the VerifyCsrfToken middleware, but you can double-check your app/Http/Kernel.php file.
For example:
protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\VerifyCsrfToken::class, // Other middleware ], ];
Note: This is a complete optional step so you may skip it if you do not find it necesaary.
10. Test the Setup
Before applying validation, test the form submission to ensure all routes, controllers, and views are functioning as expected. Temporarily bypass validation by leaving the rules() method empty:
public function rules() { return []; }
Ensure data integrity and security in Laravel
What to do after performing these steps?
Now that your setup in the Laravel ecosystem is completed, you can start adding validation rules to the Form Request class and use them in your controller to validate the form data.
How to Validate a Form Request in Laravel?
Validating the form is essential to ensure the data integrity. It saves the time and effort required to clean the data otherwise. In Laravel, form validation can be implemented in an organized and reusable way using Form Request Validation. Let’s take a look below which is a detailed explanation of how to validate a form request with the required steps.
Step 1: Create a Form Request Class
The first step in validating a form request in Laravel is to generate a custom Form Request class. The purpose of generating custom form requests is that this class will handle the validation logic for your form data.
php artisan make:request MyFormRequest
This command creates a new Form Request class in the app/Http/Requests directory. For example, if you named the request MyFormRequest, it would generate app/Http/Requests/MyFormRequest.php.
Step 2: Define Validation Rules
In the generated class, you’ll find two key methods:
- authorize(): Determines whether the user is authorized to make the request.
- rules(): Defines the validation rules for the incoming request.
Example of defining rules for a form submission:
namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class MyFormRequest extends FormRequest { public function authorize() { // Set to true to allow the request return true; } public function rules() { return [ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:users,email', 'password' => 'required|min:8|confirmed', 'age' => 'nullable|integer|min:18', ]; } public function messages() { return [ 'name.required' => 'Name is required.', 'email.required' => 'Email is required.', 'email.unique' => 'This email is already registered.', 'password.confirmed' => 'Passwords do not match.', 'age.min' => 'You must be at least 18 years old.', ]; } }
Step 3: Use the Form Request in a Controller
Instead of manually validating incoming data in your controller, inject the custom Form Request class as a dependency in the controller method. This will automatically trigger the validation logic defined in the Form Request class.
Example:
namespace App\Http\Controllers; use App\Http\Requests\MyFormRequest; class UserController extends Controller { public function store(MyFormRequest $request) { // If validation passes, you can access validated data using $request->validated() $validatedData = $request->validated(); // Example: Create a user with validated data User::create($validatedData); return response()->json(['message' => 'User created successfully!']); } }
Step 4: Handle Validation Errors
If the validation fails, Laravel automatically redirects the user back to the previous page with error messages stored in the session. You can display these errors in your view using @error or old() helper.
Example in Blade template:
<form method="POST" action="{{ route('user.store') }}"> @csrf <div> <label for="name">Name:</label> <input type="text" name="name" id="name" value="{{ old('name') }}"> @error('name') <div>{{ $message }}</div> @enderror </div> <div> <label for="email">Email:</label> <input type="email" name="email" id="email" value="{{ old('email') }}"> @error('email') <div>{{ $message }}</div> @enderror </div> <div> <label for="password">Password:</label> <input type="password" name="password" id="password"> @error('password') <div>{{ $message }}</div> @enderror </div> <button type="submit">Submit</button> </form>
Step 5: Customize Validation Error Response (Optional)
If you want to customize the validation error response (e.g., for APIs), you can override the failedValidation method in your Form Request class:
use Illuminate\Contracts\Validation\Validator; use Illuminate\Http\Exceptions\HttpResponseException; public function failedValidation(Validator $validator) { throw new HttpResponseException(response()->json([ 'status' => 'error', 'errors' => $validator->errors() ], 422)); }
Custom Validation Techniques in Laravel
Before we start setting up custom validation rules in Laravel, it is important to discuss the different techniques to get an overview and understand their usage. The three main techniques of using custom validation techniques in Laravel are using Rule Objects, Closures, and Implicit Rules.
Rule Objects
The rule object approach provides a clean, reusable method for custom validation logic. You can define a dedicated class for your rule, making it easy to maintain and extend. Here is how you can apply:
public function rules() { return [ 'name' => ['required', new Uppercase], ]; }
Closures
Developers use the Closures approach to define custom validation logic directly in the validation rules. This approach is best for quick small checks without having a separate class. You can define a closure-based rule inside the rules() method like this:
public function rules() { return [ 'email' => ['required', 'email', function ($attribute, $value, $fail) { if ($value === 'example@domain.com') { $fail($attribute.' is invalid.'); } }], ]; }
Implicit Rules
For custom Laravel validation, Implicit Rules allow developers to automatically validate logic that is directly tied to the field. Using the implicit rules approach is best when the logic is self-contained and does not require extra parameters.
Here is how to apply this implicit rule in the rules() method like so:
public function rules() { return [ 'country' => [new CheckCountry], ]; }
How to set up Laravel custom validation rules?
In order to set up custom validation rules in Laravel, define your logic to validate data that is beyond the default Laravel rules. In the below description, we have provided a step-by-step guide to create the Laravel custom validation rules:
1. Create a Custom Rule Class
Laravel provides an Artisan command to create a custom validation rule.
Run the following command to generate a new rule:
php artisan make:rule CustomRuleName
This creates a new class in the app/Rules directory. For example, if you name it Uppercase, the file will be app/Rules/Uppercase.php.
2. Implement the Validation Logic
Open the newly created rule class and implement your custom validation logic in the passes method. The passes method receives the attribute name and its value and returns true if the validation passes or false otherwise.
Example: Custom Rule to Check if a String is Uppercase
<?php namespace App\Rules; use Illuminate\Contracts\Validation\Rule; class Uppercase implements Rule { /** * Determine if the validation rule passes. * * @param string $attribute * @param mixed $value * @return bool */ public function passes($attribute, $value) { return strtoupper($value) === $value; } /** * Get the validation error message. * * @return string */ public function message() { return 'The :attribute must be uppercase.'; } }
Rule Object Approach: Using Rule Objects for Custom Validation
When setting up custom Laravel validation rules, you can create rule objects that is a structured way of handling the rules. Here is how you can do it:
Generate a Rule Object
Run the artisan command:
php artisan make:rule Uppercase
Define Validation Logic
Edit the generated class (app/Rules/Uppercase.php) to include your custom validation in the passes method:
public function passes($attribute, $value) { return strtoupper($value) === $value; } public function message() { return 'The :attribute must be uppercase.'; }
Apply the Rule
In your form request or controller, use the rule object directly:
public function rules() { return [ 'name' => ['required', new Uppercase], ]; }
The benefit of using the rule object approach keeps the validation logic modular and reusable (as stated above), which makes it a preferred choice for creating and handling complex validation scenarios.
The placement of the rule object method ensures that it is presented as an alternative that complements the Validator::extend method.
3. Use the Custom Rule in a Form Request
To use your custom rule, include it in a form request or directly in a controller.
Using in a Form Request
Create a form request class using the Artisan command:
php artisan make:request CustomRequest
In the CustomRequest class, modify the rules method to include your custom rule:
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use App\Rules\Uppercase; class CustomRequest extends FormRequest { public function rules() { return [ 'title' => ['required', 'string', new Uppercase], ]; } }
Using in a Controller
You can also use the custom rule directly in a controller:
use App\Rules\Uppercase; public function store(Request $request) { $validatedData = $request->validate([ 'title' => ['required', 'string', new Uppercase], ]); // Proceed with storing data }
4. Customizing the Error Message
The message method in your rule class allows you to define the error message. You can also pass dynamic data to the message if needed.
For example:
public function message() { return 'The :attribute field must contain only uppercase letters.'; }
5. Testing the Custom Rule
To test your custom rule, submit data via your application’s form or API and ensure the validation behaves as expected.
Example Input:
{ "title": "HELLO" }
If the value is not uppercase (e.g., “Hello”), you’ll see an error message like:
scss
The title field must contain only uppercase letters.
Additional Example: Rule to Check if a Value Contains a Specific Word
Here’s a custom rule that validates if a string contains the word “Laravel”:
<?php namespace App\Rules; use Illuminate\Contracts\Validation\Rule; class ContainsLaravel implements Rule { public function passes($attribute, $value) { return str_contains($value, 'Laravel'); } public function message() { return 'The :attribute must contain the word "Laravel".'; } }
You can use it like this:
$request->validate([ 'description' => ['required', new ContainsLaravel], ]);
The advantage of using custom validation rules in Laravel is that they are powerful and allow you to implement application-specific specific validation logic in a clean and reusable way.
Conclusion
Laravel validation rules are integral for keeping your data secure and clean. By leveraging built-in features, building web applications with Laravel gets easier and business owners can save a lot of their team by using custom Laravel validation techniques. As the spam data and users continue, using these techniques make sure you only get the relevant and accessible data.
Hire Laravel Developers in 48 Hours
Are you looking to build a website with Laravel and have all the custom Laravel validation rules? Hire Laravel developers from Devace Technologies who are skilled and have hands-on experience in leveraging Laravel custom techniques to ensure you have clean and reusable data in the best form.
Book a meeting today and take no pain in having the validation rules – let our developers handle it.
Frequently Asked Questions
How do I validate a form in Laravel?
You can validate a form in Laravel by using the validate method on the request object or leverage a Form Request class for reusable validation logic.
Here is how you can use it:
public function store(Request $request) { $validatedData = $request->validate([ 'name' => 'required|max:255', 'email' => 'required|email|unique:users', 'password' => 'required|min:8', ]); // Proceed with storing data }
The first step is to create a form request
php artisan make:request StoreUserRequest
After that, you have to add validation rules in the rules method of the generated request class:
public function rules() { return [ 'name' => 'required|max:255', 'email' => 'required|email|unique:users', 'password' => 'required|min:8', ]; }
Now, the last step is to use the Form Request in your controller:
public function store(StoreUserRequest $request) { // Validation is automatically handled }
How can I test my Laravel validation rules to ensure they’re working correctly?
This is an important factor to ensure that rules are working and doing their work. You can use Laravel’s built-in testing tools to write test cases for validation rules.
Example of Testing Validation Rules:
1. Create a test class:
php artisan make:test UserValidationTest
2. Write test methods:
public function test_email_is_required() { $response = $this->post('/users', ['email' => '']); $response->assertSessionHasErrors('email'); } public function test_email_is_valid() { $response = $this->post('/users', ['email' => 'invalid-email']); $response->assertSessionHasErrors('email'); }
Using Factories for Testing:
public function test_user_creation_with_valid_data()
{
$userData = User::factory()->make()->toArray();
$response = $this->post(‘/users’, $userData);
$response->assertStatus(302); // Assuming a redirect on success
}
How to validate a URL in Laravel?
Well, it quite easy to do that as Laravel provides a built-in URL validation rule to ensure the input is a valid URL. You can use it like this:
Basic URL Validation:
$request->validate([ 'website' => 'required|url', ]);
Customizing URL Validation with DNS Checks:
$request->validate([ 'website' => 'required|url|active_url', ]);
- url: Ensures the value is a valid URL.
- active_url: Checks if the domain of the URL has valid DNS records.
What are the built-in validation rules provided by Laravel?
Laravel offers a wide range of validation rules. Some commonly used ones include:
Rule | Description |
---|---|
required | Ensures the field is not empty. |
Verifies the input is a valid email address. | |
min:value | Sets a minimum value or string length. |
max:value | Sets a maximum value or string length. |
unique:table | Ensures the value is unique in a database table. |
exists:table,column | Ensures the value exists in a database table column. |
url | Validates that the input is a valid URL. |
numeric | Ensures the value is numeric. |
boolean | Ensures the value is either true or false. |
However, if you want a full list of built-in Laravel validation rules, refer to the Laravel validation documentation.
How do you verify an incoming form request in Laravel?
You can easily verify an incoming form request by leveraging Laravel’s built-in feature that automatically validates incoming form requests if a Form Request class is used. The Form Request handles validation, and you can access the validated data directly.
Below is an example to understand the process of verifying:
1. Create a Form Request:
php artisan make:request StoreProductRequest
2. Define validation rules in the request:
public function rules() { return [ 'name' => 'required|max:255', 'price' => 'required|numeric|min:0', 'description' => 'nullable', ]; }
3. Use the request in the controller:
public function store(StoreProductRequest $request) { $validatedData = $request->validated(); Product::create($validatedData); } By using Form Requests, Laravel ensures that validation logic is cleanly separated and automatically verified.