Laravel 10 Input Empty Space or White Space Validation Tutorial

Last Updated on by in Laravel

In this tutorial, we will learn how to add empty space in an input field in Laravel application. To build the input text white space validation functionality in Laravel we will use no additional package.

The empty space validation is the most needed to check for white spaces in the input field. This can be easily achieved using Laravel’s built-in validation rules.

Validation of user input is an integral part of web development; In Laravel, it is possible to validate white space in input field ensures that only valid data is accepted.

One such type of validation is the “no white space” validation, which ensures that no spaces are allowed in the input field. This can be useful for fields such as email addresses or passwords where spaces are not allowed.

In this guide; you will find out how to implement no white space validation in laravel form input field using laravel without_spaces form validation props.

Laravel 10 No White or Empty Space Allowed Validation Example

  • Build Laravel Application
  • Connect to Database
  • Set Up Model and Migrations
  • Build Form Validation Controller with Alpha
  • Configure View Template
  • Create New Routes
  • Run Laravel Server

Build Laravel Application

In order to ensure that the data they send is clutter-free, developers need to ensure that all inputs are correctly validated.

Hence, you have to install a new laravel app using the given command. Avoid this step if the app is already created.

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

Further, move into the application directory.

cd laravel-demo

Connect to Database

Storing information, aka data, on the database is crucial; it is easily done via adding the database credentials in the .env file.

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=

For macOS MAMP PHP server; make sure to additionally include UNIX_SOCKET and DB_SOCKET right below the database details in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

After running the migrations, we will create the needed table and rows in the database.

php artisan migrate

Build Form Controller

In Laravel, you can write separate logic in a separate controller file. You must invoke the given artisan command from the terminal to generate the new controller.

php artisan make:controller UserController

Head over to the app/Http/Controllers/ directory; next, you need to create UserController.php file and define the following code into the file.

<?php

namespace App\Http\Controllers;

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

class UserController extends Controller
{

    public function index()
    {
        return view('user');
    }
    

    public function userForm(Request $request)
    {
        Validator::extend('without_spaces', function($attr, $value){
            return preg_match('/^\S*$/u', $value);
        });
  
        $request->validate([
                'name' => 'required',
                'username' => 'required|without_spaces',
            ],
            [
                'username.without_spaces' => 'Whitespace not allowed.'
            ]);
     
        $input = $request->all();
        $user = User::create($input);
      
        return back()->with('success', 'User data has been stored.');
    }
}

Configure View Template

When developing applications with Laravel, it is essential to ensure that a view template is created and connected to the controller.

You have to get into the resources/views/ folder and create the user.blade.php file with the provided code.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <title>Laravel</title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}">
</head>

<body>
    <div class="container mt-5">

       <h2 class="mb-4">Laravel No White Space Validation Example</h2>

        @if(Session::has('success'))
            <div class="alert alert-success text-center">
                {{Session::get('success')}}
            </div>
        @endif    

        <form  method="post" action="{{ route('empty-validate.form') }}" novalidate>

            @csrf

            <div class="form-group mb-2">
                <label>Name</label>
                <input type="text" class="form-control @error('name') is-invalid @enderror" name="name" id="name">

                @error('name')
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $message }}</strong>
                    </span>
                @enderror
            </div>

            <div class="form-group mb-2">
                <label>User name</label>
                <input type="text" class="form-control @error('username') is-invalid @enderror" name="username" id="username">

                @error('username')
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $message }}</strong>
                    </span>
                @enderror
            </div>            

            <div class="d-grid mt-3">
              <input type="submit" name="send" value="Submit" class="btn btn-dark btn-block">
            </div>
        </form>
    </div>
</body>

</html>

Create New Routes

To create new routes in Laravel, you can define them in the routes/web.php file (for web routes) or routes/api.php file (for API routes).

Here’s an example of how to define basic routes in Laravel:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

/*
|--------------------------------------------------------------------------
| 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('/', [UserController::class, 'index']);
Route::post('/validate', [UserController::class, 'userForm'])->name('empty-validate.form');

Run Laravel Server

To run a Laravel application, you have to run the following command. To view the app on the browser use the given url.

php artisan serve
http://127.0.0.1:8000

Laravel Input Empty Space or White Space Validation Tutorial

Conclusion

One of the most common validations is to prevent users from entering white space in their input fields.

This can be quickly done using Laravel’s built-in validation rules. With these rules, you can ensure that your application does not accept any input containing white space and only accepts valid data.

Laravel provides a straightforward way of validating inputs to ensure that no white spaces are included.

This dramatically helps laravel developers avoid common errors caused by empty or invalid inputs and ensures that their code runs smoothly without hiccups.

In this post, we learned how to not allowed white space in the laravel form input field using built-in laravel validation rules.

With Laravel’s robust input validation, it has become easier for developers to have complete control over input fields.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.