How To Create Validation Rule In Laravel 10

Websolutionstuff | May-22-2023 | Categories : Laravel

In this article, we will see how to create a validation rule in laravel 10. Here, we will learn about the laravel 10 custom validation rule. In this article, we will create a custom form request validation rule in laravel 10. 

Laravel provides several different approaches to validate your application's incoming data. Laravel includes a wide variety of convenient validation rules that you may apply to data, even providing the ability to validate if values are unique in a given database table.

So, let's see the laravel 10 custom validation rule, laravel 10 custom validation rule example, laravel 10 custom validation rule with parameters, laravel validation, and laravel request validation.

Laravel provides a variety of helpful validation rules; however, you may wish to specify some of your own. One method of registering custom validation rules is using rule objects. To generate a new rule object, you may use the make:rule Artisan command.

Step 1: Install Laravel 10

In this step, we will install laravel 10 using the following command.

composer create-project laravel/laravel laravel_10_validation_example

 

Step 2: Create Routes

Then, we will create a route to the web.php file. So, add the below code to that file.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\UsersController;
   
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
    
Route::get('index', [UsersController::class, 'create']);
Route::post('store', [UsersController::class, 'store'])->name('store');

 

Step 3: Create Validation Rule

Let's use this command to generate a rule that verifies a string is uppercase. Laravel will place the new rule in the app/Rules directory. If this directory does not exist, Laravel will create it when you execute the Artisan command to create your rule

php artisan make:rule Uppercase

app/Rules/Uppercase.php

<?php
 
namespace App\Rules;
 
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
 
class Uppercase implements ValidationRule
{
    /**
     * Run the validation rule.
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (strtoupper($value) !== $value) {
            $fail('The :attribute must be uppercase.');
        }
    }
}
 
Step 4: Create Controller

Now, we will create UsersController using the following code. And add the following code to that file.

php artisan make:controller UsersController

app/Http/Controllers/UsersController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use App\Rules\Uppercase;
   
class UsersController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(): View
    {
        return view('index');
    }
        
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request): RedirectResponse
    {
        $validatedData = $request->validate([
            'name' => ['required', 'string', new Uppercase],
            'email' => 'required|email'
        ]);

        $user = User::create($validatedData);
                    
        return back()->with('success', 'User created successfully.');
    }
}

 

Step 5: Create View File

Then, we will create an index.blade.php file. So, add the following HTML code to that file.

<!DOCTYPE html>
<html>
<head>
    <title>How To Create Validation Rule In Laravel 10 - Websolutionstuff</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
      
        <h1>How To Create Validation Rule In Laravel 10 - Websolutionstuff</h1>
         
        <form method="POST" action="{{ route('custom.validation.post') }}">
        
            {{ csrf_field() }}
        
            <div class="mb-3">
                <label class="form-label" for="inputName">Name:</label>
                <input type="text" name="name" id="inputName" class="form-control @error('name') is-invalid @enderror" placeholder="Name">
    
                @error('name')
                    <span class="text-danger">{{ $message }}</span>
                @enderror
            </div>
         
            <div class="mb-3">
                <label class="form-label" for="inputEmail">Email:</label>
                <input type="email" name="email" id="inputEmail" class="form-control @error('email') is-invalid @enderror" placeholder="Email">
    
                @error('email')
                    <span class="text-danger">{{ $message }}</span>
                @endif
            </div>
       
            <div class="mb-3">
                <button class="btn btn-success btn-submit">Submit</button>
            </div>
        </form>
    </div>
</body>
</html>

 


You might also like:

Recommended Post
Featured Post
How to Create Trait in Laravel 10 Example
How to Create Trait in Laravel...

Hello developers! 👋 Today, let's dive into the wonderful world of Laravel 10 and explore one of its handy featu...

Read More

Feb-09-2024

StartOf And EndOf Functions Example Of Carbon
StartOf And EndOf Functions Ex...

In this article, we will see startof and endof functions example of carbon in laravel. As you all know carbon provide ma...

Read More

Dec-19-2020

How To Generate RSS Feed In Laravel 9
How To Generate RSS Feed In La...

In this article, we will see how to generate an RSS feed in laravel 9. Here, we will generate an RSS feed in larave...

Read More

Dec-12-2022

How to Image Upload with Preview in Angular 17
How to Image Upload with Previ...

In this article, we'll see how to image upload with a preview in angular 17. Here, we'll learn about the an...

Read More

Apr-01-2024