Space Not Allowed Validation in Laravel Example

Space Not Allowed Validation in Laravel Example

Hello friends, Today we will show demonstration of laravel validation not allow spaces. In this example we will show how to username in Laravel to only accept letters, numbers, underscores and dashes not space. This post we simply provide example of space not allowed validation in laravel. You just required to some step to done laravel validation without white spaces.

Sometime we need to add not allow whitespace validation in laravel. So we will show how to add validation for not allow white space validation in laravel 7 and laravel 8 using regex. we will create custom validation for no space allow in laravel.

Read Also :  How Generate PDF From HTML In Laravel dompdf

In this post we will provide add no allow space validation in laravel. You can also follow Laravel 8 Form Validation Example with this code: Laravel 8 Form Validation Example

Example : Laravel validation no space allowed

<?php
    
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use App\User;
use Validator;
    
class HomeController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('createUser');
    }
    
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        Validator::extend('without_spaces', function($attr, $value){
            return preg_match('/^\S*$/u', $value);
        });
  
        $request->validate([
                'name' => 'required',
                'username' => 'required|without_spaces',
                'email' => 'required|email|unique:users'
            ],
            [
                'username.without_spaces' => 'Whitespace not allowed.'
            ]);
     
        $input = $request->all();
        $user = User::create($input);
      
        return back()->with('success', 'User created successfully.');
    }
}

I hope you understand of Laravel space not allowed validation and it can help you…

Read Also :  Laravel Dynamic Dependent Select Box using jQuery Ajax