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:
= $min && strlen($value)Using the Validator Class
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.
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';Benefits of Using a Validator Class
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3