Home >Backend Development >PHP Tutorial >How to extract a simple validator class in PHP?
I previously learned how to create a form and validate it, and then store the form data in a database. Today, I learned how to extract a Validator Class from the form validation code, making it reusable and modular.
A Validator Class is a way to group together functions that check if user input is correct. It helps to ensure that the data entered by a user meets certain rules or criteria.
A pure function is a function that is not contingent or dependent upon state or value from the outside world. In other words, a pure function:
The Validator Class contains pure functions that are used to validate input data. In today code, functions are:
<?php class Validator { public static function string($value, $min = 1, $max = INF) { $value = trim($value); return strlen($value) >= $min && strlen($value) <= $max; } public static function email($value) { return filter_var($value, FILTER_VALIDATE_EMAIL); } }
To use the Validator Class, we include it in our PHP file and call its methods using the Class Name::Method Syntax . We can then use conditional statements to check if the input data is valid. For example:
If the email is valid, we can move the user to the next screen. Otherwise, we can display an error message.
<?php require 'Validator.php'; $config = require 'config.php'; $db = new Database($config['database']); $heading = 'Create Note'; if(! Validator::email('mujtabaofficial247@gmail.com')){ dd('that is not a valid email');}
As the given email is correct then move to execute next code. If the input body is valid, we can insert it into the database. Otherwise, we can display an error message.
if ($_SERVER['REQUEST_METHOD'] === 'POST') { $errors = []; if (! Validator::string($_POST['body'], 1, 1000)) { $errors['body'] = 'A body of no more than 1,000 characters is required.'; } if (empty($errors)) { $db->query('INSERT INTO notes(body, user_id) VALUES(:body, :user_id)', [ 'body' => $_POST['body'], 'user_id' => 1 ]); } } require 'views/note-create.view.php';
Using a Validator Class provides several benefits, including:
By extracting a simple Validator Class, we can ensure that our user input data is validated consistently throughout our application.
I hope that you have clearly understood this.
The above is the detailed content of How to extract a simple validator class in PHP?. For more information, please follow other related articles on the PHP Chinese website!