DEV Community

Ghulam Mujtaba
Ghulam Mujtaba

Posted on

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.
<?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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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.

<?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');}

Enter fullscreen mode Exit fullscreen mode

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';

Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)