"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to extract a simple validator class in PHP?

How to extract a simple validator class in PHP?

Published on 2024-07-31
Browse:769

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.

Introduction

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.

Pure Functions

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:

  • Always returns the same output given the same inputs.
  • Has no side effects, meaning it doesn't modify any external state.
  • Doesn't rely on any external state, only on its input parameters.

Validator Class

The Validator Class contains pure functions that are used to validate input data. In today code, functions are:

  • string(): Checks if the input value is a string within a specified length range.
    • Uses trim() to remove whitespace characters
    • Uses strlen() to check the length of the input data
  • email(): Validates an email address using the filter_var function.
= $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:

  • Reusability: Validator functions can be reused throughout the application.
  • Modularity: Validator logic is separated from the main application code.
  • Easier Maintenance: Validator functions can be updated or modified without affecting the main application code.

Conclusion

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.

Release Statement This article is reproduced at: https://dev.to/ghulam_mujtaba_247/how-to-extract-a-simple-validator-class-in-php-3pp6?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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