Adding custom validation errors to Laravel form

Asked
Active3 hr before
Viewed126 times

8 Answers

errorsvalidationaddingcustom
90%

or instead you can call $validator->validate() – Tebe Sep 17 at 23:10 ,There is no way to append errors to existing validator and make it fail. You can only create a new validator with custom errors like this:,If you don't like the idea of abusing required validation rule for custom appended errors, you can always extend Laravel Validator with custom rules. I added a generic failkey rule and made it mandatory this way:,Rather than handling the logic to tell the user their password is incorrect myself, I'd rather just add a form error to the password input so it shows up just like regular form validation. Something like so:

One way to implement it though.

// inside if(Auth::validate)
if (User::where('email', $email) - > first()) {
   $validator - > getMessageBag() - > add('password', 'Password wrong');
} else {
   $validator - > getMessageBag() - > add('email', 'Email not found');
}
load more v
88%

Creating Form Requests,Preparing Input For Validation,Authorizing Form Requests,After Validation Hook

First, let's assume we have the following routes defined in our routes/web.php file:

use App\ Http\ Controllers\ PostController;

Route::get('/post/create', [PostController::class, 'create']);
Route::post('/post', [PostController::class, 'store']);
load more v
72%

Laravel validation for multiple files in array,so, let's see bellow three way to change validation error message in laravel 7 application.,Today, i will let you know example of laravel validation custom error messages. you'll learn custom error message laravel validator. In this article, we will implement a laravel custom validation message in controller. This article goes in detailed on laravel form validation custom error messages., * Get the error messages for the defined validation rules.

namespace App\ Http\ Controllers;
use Illuminate\ Http\ Request;
use App\ User;
class UserController extends Controller {
   /**     * Display a listing of the resource.     *     * @return \Illuminate\Http\Response     */
   public
   function index(Request $request) {
      $users = User::all();
      return view('users.index', compact('users'));
   } /**     * Store a newly created resource in storage.     *     * @param  \Illuminate\Http\Request  $request     * @return \Illuminate\Http\Response     */
   public
   function store(Request $request) {
      $request - > validate(['name' => 'required', 'email' => 'required|email|unique:users,email', 'password' => 'required|same:confirm_password']);
      $input = $request - > all();
      $input['password'] = bcrypt($input['password']);
      User::create($input);
      return redirect(route('users.index'));
   }
}
load more v
65%

Validating in Laravel can be really simple for instance take this example:,For simple validation, this is amazing! simple and effective but in cases when you need to add a custom error message to the error object this cannot be used instead use the Validator class and pass in the request object and an array of rules.,This can be simplified further by instead writing:,Calling ->fails() executes the validation and will redirect with input and errors upon failure.

Validating in Laravel can be really simple for instance take this example:

request() - > validate([
   'due_date' => 'required',
   'template' => 'required'
]);
load more v
75%

Let's also create the routes for our demo contact form, add the following to your routes file:,Let's add our validation rules, paste the code below to the newly created ContactFormRequest file:,Next, let's create a controller with the respective methods to handle the routes we created.,Before doing any kind of custom error messages, let's see how the default Laravel validation error messages look like. Let's start our demo contact form:

Let's create a new Laravel application, I prefer using Laravel installer, you are free to use any method that is most convienient for you.

laravel new laravel - custom - validation - error - messages
load more v
40%

Step 2: Setup Database Credentials,Step 1: Install Laravel Application,shweta on Laravel 7 Unique Validation Example Tutorial,In this step, Add database credentials in the .env file:

First of all, Open your command prompt and run the following command:

composer create - project--prefer - dist laravel / laravel Blog

In this step, Add database credentials in the .env file:

DB_CONNECTION = mysql
DB_HOST = 127.0 .0 .1
DB_PORT = 3306
DB_DATABASE = here your database name here
DB_USERNAME = here database username here
DB_PASSWORD = here database password here

Next, Open your command prompt and run the following command for migration:

php artisan migrate
Route::get('form', 'Cu[email protected]');
Route::post('store', '[email protected]');

In this step, open your command prompt and run the following command to generate custom error message controller:

php artisan make: controller CustomErrorController
namespace App\ Http\ Controllers;

use Illuminate\ Http\ Request;
use App\ User;

class CustomErrorController extends Controller {
   public
   function create() {
      return view('form');
   }

   public
   function store(Request $request) {
      $request - > validate(
         [
            'name' => 'required',
            'password' => 'required|min:5',
            'email' => 'required|email|unique:users'
         ],
         [
            'name.required' => 'Name is required',
            'password.required' => 'Password is required'
         ]
      );

      $input = $request - > all();
      $input['password'] = bcrypt($input['password']);
      $user = User::create($input);

      return back() - > with('success', 'User created successfully.');
   }
}
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Custom Validation Error Message Example Tutorial -Tutsmake.com</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="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
  
        <h1>Laravel Custom Validation Error Message Example</h1>
   
        @if(Session::has('success'))
        <div class="alert alert-success">
            {{ Session::get('success') }}
            @php
                Session::forget('success');
            @endphp
        </div>
        @endif
   
        <form method="POST" action="{{ route('store') }}">
  
            @csrf
  
            <div class="form-group">
                <label>Name:</label>
                <input type="text" name="name" class="form-control" placeholder="Name">
                @if ($errors->has('name'))
                    <span class="text-danger">{{ $errors->first('name') }}</span>
                @endif
            </div>
   
            <div class="form-group">
                <label>Password:</label>
                <input type="password" name="password" class="form-control" placeholder="Password">
                @if ($errors->has('password'))
                    <span class="text-danger">{{ $errors->first('password') }}</span>
                @endif
            </div>
    
            <div class="form-group">
                <strong>Email:</strong>
                <input type="text" name="email" class="form-control" placeholder="Email">
                @if ($errors->has('email'))
                    <span class="text-danger">{{ $errors->first('email') }}</span>
                @endif
            </div>
   
            <div class="form-group">
                <button class="btn btn-success btn-submit">Submit</button>
            </div>
        </form>
    </div>
</body>
</html>

In this step, we will use the PHP artisan serve command. It will start your server locally

php artisan serveIf you want to run the project diffrent port so use this below command php artisan serve--port = 8080

Now we are ready to run our example so run bellow command to quick run.

http: //localhost:8000/form
load more v
22%

In this tutorial, we’ll go over how you can validate a form in Laravel using the available methods and create custom validation rules in Laravel.,In this tutorial, we went over how to use validation in Laravel using the built-in rules and using a custom rule. Validation is very important, as it ensures that all the data that are going into your system are of a specific necessary format or are secure. That’s why it’s essential to understand and master validation.,Another way to use multiple validation rules is using an array for the value rather than a string:,Let’s start by first using the validate function, passing it the data received from the form using $request->all(), then we’ll add the validation rules one by one to the second parameter array:

composer create - project laravel / laravel validation - tutorial
load more v
60%

Search Answer Titles

$this - > validate([
   'userid' => 'required|min:3|max:100',
   'username' => 'required|min:3',
   'password' => 'required|max:15|confirmed',
], [], [
   'userid' => 'User ID'
]);
load more v