-
Notifications
You must be signed in to change notification settings - Fork 5
Data Validation
Hossein Pira edited this page Sep 11, 2023
·
9 revisions
A model used to validate input data to the application. This model is very modern and customizable as well as translatable.
Key | Description |
---|---|
url | Field for validating URLs |
number | Field for validating numeric values |
min | Field for validating minimum string length |
max | Field for validating maximum string length |
required | Field for validating required values |
regex | Field for validating values using regular expression |
Field for validating email addresses |
For example in a controller I call:
<?php
namespace Monster\App\Controllers;
use Monster\App\Models\Validation;
class HomeController
{
public function index()
{
$data = [
'name' => 'John Doe',
'email' => '[email protected]',
'age' => 19
];
$rules = [
'name' => 'required',
'email' => 'required|email',
'age' => 'number|min:1|max:3'
];
$validator = new Validation($data, $rules);
if ($validator->validate()) {
echo 'Data is valid!';
} else {
$errors = $validator->getErrors();
print_r($errors);
}
}
}
'username' => 'required|regex:/^[a-zA-Z0-9_]+$/'
To translate the errors into the third value of the Validation class
, enter the name of your language file located in the routes/lang/errors
folder. For example en.php
file:
<?php
return [
'required' => 'The :key field is required.',
'min' => 'The :key must be at least :value characters.',
'max' => 'The :key may not be greater than :value characters.',
'email' => 'The :key must be a valid email address.',
'regex' => 'The :key format is invalid.',
'number' => 'The :key field must be a number.',
'url' => 'The :key must be a valid URL.',
'error' => 'Unknown error for :key',
];
$validator = new Validation($data, $rules, 'en');
The default language is English. I hope you enjoy this model as well as the previous models.
if ($validator->validate()) {
echo "Validation passed! 😄";
} else {
// Get the validation errors
$errors = $validator->getErrors();
foreach ($errors as $field => $messages) {
foreach ($messages as $message) {
echo "Error in field '{$field}': {$message} 😢<br />";
}
}
}
- 1 - Installation
- 2 - Routing And Database
- 3 - HTTP Request
- 4 - CORS
- 5 - Env File
- 6 - Views
- 7 - Language
- 8 - SPA Without API
- 9 - Data Validation
- 1 - Installation
- 2 - Routing And Database
- 3 - HTTP Request
- 4 - CORS
- 5 - Env File
- 6 - Views
- 7 - Language
- 8 - SPA Without API
- 9 - Data Validation