Laravel Custom Validation no Space Allowed

In Laravel, you can create custom validation rules to add additional validation logic to your application’s form requests. Here’s an example that demonstrates how to create a custom validation rule to disallow spaces in a field.

More than time we need a username in Laravel to only accept letters, numbers, dashes and underscores and not space inside username validation custom rules.

Solution 1: Using Regex

You can use the regex validation to avoid the space in your username or any other field.

'username' => [required|min:6|regex:/^\S*$/u|unique:users,username],

Solution 2: Using Validator Facade

 To implement a custom validation rule that disallows spaces in a field, you can use the Validator facade.

  1. Create a custom validation rule class. Open a new file, let’s say NoSpaceRule.php, and add the following code:
phpCopy code<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class NoSpaceRule implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return !preg_match('/\s/', $value);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must not contain spaces.';
    }
}

In this example, we create a custom validation rule called NoSpaceRule. The passes method checks if the given value contains any whitespace characters using a regular expression (\s). If it finds any spaces, it returns false, indicating a validation failure.

The message method defines the error message that will be shown when the validation fails.

  1. Next, you can use the custom validation rule in your controller or request validation logic. For example:
phpCopy code<?php

namespace App\Http\Controllers;

use App\Rules\NoSpaceRule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username' => ['required', new NoSpaceRule],
            // Other validation rules...
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        // Process the request if validation passes
    }
}

In this example, we import the NoSpaceRule class and use it as a validation rule for the 'username' field. The rule is added as a new instance of the NoSpaceRule class in the validation rules array.

If the validation fails, the controller can handle the error by redirecting back to the previous page with the validation errors and input data.

That’s it! You’ve created a custom validation rule in Laravel that disallows spaces in a field.

Leave a Comment