Skip to content

Data Validation

Hossein Pira edited this page Sep 11, 2023 · 9 revisions

Validation

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
email Field for validating email addresses

Example

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' => 'john.doe@example.com',
            '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);
        }
    }
}

Custom Regular Expression Rules (Regex)

'username' => 'required|regex:/^[a-zA-Z0-9_]+$/'

Translation

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.

Foreach Errors

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 />";
        }
    }
}