Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to validate exact words in Laravel?
Laravel provides several methods to validate exact words in your application. The most common approaches include using Rule::in method, in: validation rule, and regular expressions for precise word matching.
Using Rule::in Method
The Rule::in method validates that the field value matches one of the specified values exactly. To use this method, you need to import the Rule class ?
Make sure to include: use Illuminate\Validation\Rule; at the top of your file.
<?php
$input = [
'category' => ['ABC', 'XYZ'],
];
Validator::make($input, [
'category' => [
'required',
'array',
Rule::in(['ABC', 'TIK']),
],
]);
?>
Here the input array has category values ABC and XYZ, but Rule::in expects ABC and TIK. Since XYZ doesn't match TIK, this validation will fail.
Single Word Validation
For validating a single exact word using Rule::in ?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
class TestController extends Controller {
public function index() {
$input = array("name" => "Riyan");
$rules = [
'name' => [Rule::in(['Riyan'])]
];
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
echo "Word does not match";
} else {
echo "Word matches";
}
}
}
?>
Word matches
Using in: Validation Rule
Laravel also provides a shorthand in: rule for exact word matching ?
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Validator;
class TestController extends Controller {
public function index() {
$input = array("name" => "Disha");
$rules = [
'name' => 'in:Disha',
];
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
echo "Word does not match";
} else {
echo "Word matches";
}
}
}
?>
Word matches
Using Regular Expressions
For more precise control, you can use regular expressions with anchors to match exact words ?
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Validator;
class TestController extends Controller {
public function index() {
$input = array("name" => "Disha");
$rules = [
'name' => 'regex:/^Disha$/',
];
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
echo "Word does not match";
} else {
echo "Word matches";
}
}
}
?>
Word matches
Comparison of Methods
| Method | Use Case | Syntax |
|---|---|---|
| Rule::in | Multiple exact values | Rule::in(['value1', 'value2']) |
| in: rule | Simple exact matching | 'in:value1,value2' |
| regex | Patternbased validation | 'regex:/^pattern$/' |
Conclusion
Laravel offers flexible word validation through Rule::in, in: rules, and regex patterns. Choose Rule::in for multiple values, in: for simple cases, and regex for complex pattern matching requirements.
