How to validate only alphabet and space inputs entry in Laravel in the best way?

Laravel validation rules can be customized. As per the input fields, we can define any type of validation rules for the user entry. There can be numerous types of input validations. For example, email, mobile number, string text, alphanumeric and so. In this tutorial, we will learn of new ways for only alphabet and space inputs validation in Laravel.

Laravel provides a variety of helpful validation rules. However, you can specify some of your own validation rules. One way to register custom validation rules is using the Validator::extend method.

Validator::extend('alphanumeric', function($attribute, $value, $parameters)
    return $value == 'alphanumeric';

The alpha_dash rule

The field under validation may have alpha-numeric characters, as well as dashes and underscores.

The custom validator gets in three arguments: the name of the $attribute being validated, the $value of the attribute, and an array of the $parameters passed to the rule.

Using the same template, we can define a pattern for only alpha numeric and spaces in a string.

Validator::extend('alpha_spaces', function($attribute, $value)
    return preg_match('/^[\pL\s]+$/u', $value);

The above code checks if the input parameters, defined in the $value variable match the alpha_spaces criteria. The regex pattern inside the preg_match function checks for only alphabets and spaces entries inside the input parameter.

You can use the Validator::extend method to test any regex pattern and inputs. The pattern below is to assure entry for only alphabet and space inputs.