How to validate exact words in Laravel?


To validate data you can make use of the Validation class. The validation helps to validate data as well as to display error messages to the user.

To get the exact words to validate you can make use of Rule::in method available with laravel.

Using Rule::in method whatever the values provided by this rule has to be matched otherwise it will fail.

Example 1

working with Rule::in method

To work with Rule::in method you need to include the class : use Illuminate\Validation\Rule; or use Rule;

$input = [ 'category' => ['ABC', 'XYZ'], ]; Validator::make($input, [ 'category' => [ 'required', 'array', Rule::in(['ABC', 'TIK']), ], ]);

Here the $input array has a category with values ABC and XYZ. The Rule::in has an array of two values ABC and TIK. THe Rule::in expects the array to match exactly with the one given in the input data , if not it will fail.

Since the Rule::in says its ABC and TIK which is not matching with ABC and XYZ. Hence the above validation on $input will fail.

Example 2

In this example we will test a exact word to be matched using Rule::in

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use Illuminate\Routing\Router; use Illuminate\Validation\Rule; class testuserip extends Controller { public function index() { $input = array("name" => "Riyan"); $rules = [ 'name' => [ Rule::in('Riyan')] ]; // validate $validator = Validator::make($input, $rules); if ($validator->fails()) { echo "Word does not match"; } else { echo "Word matches"; } } }

Output

The output of the above code is −

Word matches

Example 3

In this example will make use of the in: expression to test the exact words −

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use Illuminate\Routing\Router; use Illuminate\Validation\Rule; class testuserip extends Controller { public function index() { $input = array("name" => "Disha"); $rules = [ 'name' => 'in:Disha', ]; // validate $validator = Validator::make($input, $rules); if ($validator->fails()) { echo "Word does not match"; } else { echo "Word matches"; } } }

Output

The output of the above code is −

Word matches

Example 4

You can make use of regular expression inside the rule as shown in the example below −

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use Illuminate\Routing\Router; use Illuminate\Validation\Rule; class testuserip extends Controller { public function index() { $input = array("name" => "Disha"); $rules = [ 'name' => 'regex:/^Disha$/', ]; // validate $validator = Validator::make($input, $rules); if ($validator->fails()) { echo "Word does not match"; } else { echo "Word matches"; } } }

Output

The output of the above code is −

Word matches

Updated on: 01-Sep-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements