How to use the maximum characters validation work in Laravel in the best way?

Maximum characters validation refers to the length constraint of a string field. To test length, there are many techniques for HTTP tests. We can verify how validation works.

You can use maximum characters validation in many cases. For example, limit the length of a user’s real name to 50 characters, or to restrict the email address to the database column length of 255. In addition to database constraints, you can add validation constraints to the controller while creating and updating records.

Laravel has a User model and a factory that goes along with the model. We will use this to demonstrate our testing techniques.

Step 1: Set up a new Laravel Project

laravel new length-validation
cd length-validation

Next we can create a Controller.

php artisan make:controller UsersController
php artisan make:test UserTest

Next step is to add a route in routes/web.php.

Route::post('/users', 'UsersController@save');

Step 2: Set up validation

Once the controller and required routes are set up. On validation success, we should return a simple JSON response. Let’s check how we can do this length validation.

<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class UsersController extends Controller
{
    public function save(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|max:50',
            'email' => 'required|email|max:255',
        ]);
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
        ]);
    }
}

The max validation rule is used to check the maximum length value on our fields.

First, we see how to test to ensure that validation fails when input values are over the max value. Our purpose is to define the business requirements for length. When changed, this triggers failed tests. If we remove the max requirement, the tests act as a safety shield to remind us of the rules associated with the data.

To ensure the inner bounds of length validation, it ensures that always the right amount of length is passed.

** @test */
function name_validation()
{
    $response = $this->post('/users', [
        'name' => str_repeat('a', 50),
        'email' => $this->user->email,
        'password' => 'secret',
    ]);
    $this->assertDatabaseHas('users', [
        'email' => $this->user->email,
    ]);
    $response->assertStatus(201);
}

The test above ensures that a ‘name’ with the right length is passed.

String columns entered from Laravel application typically should have some validation length that associates with the database column type (i.e. varchar(255)). Testing the max length allowed ensures that controllers validate strings before they are inserted into the database improperly.