How to extract a simple validator class in PHP?

WBOY
发布: 2024-07-17 13:57:12
原创
372 人浏览过

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) <= $max;
    }

    public static function email($value) {
        return filter_var($value, FILTER_VALIDATE_EMAIL);
    }
}
登录后复制

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.

以上是How to extract a simple validator class in PHP?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!