定制 priteshyadav444/validation 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

priteshyadav444/validation

Composer 安装命令:

composer require priteshyadav444/validation

包简介

The library is inspired by Laravel validation and provides limited but similar functionality for form validation in Core PHP.

README 文档

README

The library is inspired by Laravel validation and provides limited but similar functionality for form validation. It allows developers to define validation rules in a simple, human-readable format (e.g. "required|numeric") and quickly validate user input. This helps to ensure that the data entered into forms is accurate, consistent, and meets certain standards, improving the overall user experience and reducing the risk of errors in the application.

This library provides classes for validating different types of data inputs in PHP. It includes the following classes:

  • Validate: contains functions for validating individual inputs, such as strings, numbers, and passwords.
  • FormValidator: uses the Validate class to validate form inputs and return errors.
  • FileValidator: it validate and uploading files. it takes in a $_FILES object and a key to identify the file, and a target directory to upload the file.
  • ErrorHandler: returns error messages and it methods to handle errors for each particular form input.

Features

  • Easy to Use
  • API like Laravel
  • File handling
  • Validation
  • Error handling

Requirements

  • PHP 7.0 or above.

Usage - How to use in core Php Form Validation

FormValidator Class

The FormValidator class uses the Validate class to validate form inputs and return errors using Error Class. How to Use :

  1. Include the FormValidator class in your code by using require or include statement.

  2. Create an instance of the FormValidator class and store it in a variable.

  3. Call the validate method on the instance of the FormValidator class and pass the form data and validation rules to it as arguments.

  4. The validate method will validate the form data based on the rules and return true if the data is valid, and false otherwise.

  5. If the validate method returns false, you can access the error messages using the errors method on the instance of the FormValidator class.

    $path = "../../validation/validators/FormValidator.php"; 
    indlude "$path";
    use Validators\{FormValidator, FileValidator};
    $obj = new FormValidator();
    
    if (isset($_POST['submit'])) {
    $validations = [
        'name' => 'string',
        'email' => 'email',
        'phone' => 'numeric|min:10|max:10',
        'docs' => 'required|filetype:txt'
    ];
    
    if (!$obj->validate($_POST, $validations)->isError()) {
        $file = new FileValidator($_FILES, "docs", "files");
        $file->upload();
        }
    }
    

FormValidator class uses ErrorHandler Class to Handle Error : Using isErro() method and all() we can list errors :

if ($obj->isError() != false) {
        echo '<div class="alert alert-danger" role="alert">';
        foreach ($obj->all() as $error)
            echo "<li>$error</li>";
        echo '</div>';
}

To populate old value which was valid we can use old() method.

<div class="mb-3">
  <label for="name" class="form-label">Name</label>
  <input type="text" name="name" value='<?php echo "{$obj->old('name')}"; ?>' class="form-control" id="name" >
</div>
<div class="mb-3">
  <label for="email" class="form-label">Email</label>
  <input type="email" oninvalid="InvalidMsg(this);" oninput="InvalidMsg(this);" name="email" value='<?php echo "{$obj->old('email')}"; ?>' class="form-control" id="email" aria-describedby="emailHelp">
</div>
<div class="mb-3">
  <label for="phone" class="form-label">Phone</label>
  <input type="text" name="phone" value='<?php echo "{$obj->old('phone')}"; ?>' class="form-control" id="phone">
</div>

ErrorHandler Class

The ErrorHandle class provides functions to handle and store error messages. The class has functions to set error messages, return all error messages, check if errors exist, and handle error messages.

  1. isError() : method checks if there are any errors stored in the object's $errors array and returns a boolean value indicating the presence of errors. If a $key is passed as a parameter, it will check if there are any errors stored for that specific key in the $errors array and return a boolean value accordingly.
  2. all() : method returns an array of all error messages stored in the object's $errors array.
  3. old($key): The old method is a function in a PHP class used to return old values if the data was valid. It takes a single parameter, $key, which is used to retrieve the value from an array called oldValues.

Validate Class

This is a PHP class named "Validate" that provides functions to validate different data types (integer, float, string, email, password) and also functions to get different data types (integer, string, length). The class also includes error handling functionality through inheritance of the "ErrorHandler" class. Following method :

  1. isInt: Validates whether the input is an integer or not.

  2. isfloat: Validates whether the input is a floating-point number or not.

  3. isString: Validates whether the input is a string or not.

  4. isEmail: Validates whether the input is a valid email address or not.

  5. getInt: Returns the input as an integer, floating-point number or boolean (false) if it is not valid.

  6. getString: Returns the input as a string or boolean (false) if it is not a valid string.

  7. getLength: Returns the length of the input.

  8. checkMinimum: Checks if the length of the input is greater than or equal to the specified length.

  9. checkMaximum: Checks if the length of the input is less than or equal to the specified length.

  10. checkPassword: Validates the input as a password according to the specified regular expression.

  11. extractInteger: Extracts only the integer part from the input.

  12. extractFloat: Extracts only the floating-point number part from the input.

  13. senitizeInput : method is a security measure used to sanitize user input. It performs the following operations in the given order:

    • Removes any whitespace from the beginning and end of the input string with trim().

    • Strips backslashes (\) from the input string with stripslashes().

    • Converts any special HTML characters in the input string to their corresponding HTML entities with htmlspecialchars().

The purpose of these operations is to make sure that the input data is free from any malicious content, such as scripts, that could potentially harm the application. The method returns the sanitized input as the result.

Steps to Add custom validation in this library:

  1. Create a validation method in the Validate Class that returns a boolean value. For example: public function checkEmail():bool in the Validate class.

  2. Map the validation key to the validation type in the match function inside getValidationType() in the FormValidation Class. For example, 'email' => CHECK_EMAIL.

  3. Map the $validationType to an error code in the getErrorMessage() method in the errorHandler class. For example, 'CHECK_EMAIL' => 'INVALID_DATATYPE_KEY'.

  4. Map the $errorCode to an error message in the $errorHandler property in the errorHandler class.. For example, 'INVALID_DATATYPE_KEY' => 'Invalid Data types'.

  5. Add a conditional statement for $validationType (CHECK_EMAIL) in the performValidation() method in FormValidator.

    • Test using Validate Class method to perform the validation, If the validation fails call the setError() method, and
    • Pass the error message using the getErrorMessage() method by passing the $validationType (If the validation fails) and other required arguments.

Important Notice for Library Users

Please be aware that this library has not been fully tested and may contain bugs. If you encounter any issues while using this library, we kindly request that you report them in the Issues section of this repository. This will allow us to identify and resolve any problems as soon as possible.

Thank you for your understanding and cooperation.

priteshyadav444/validation 适用场景与选型建议

priteshyadav444/validation 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 8 次下载、GitHub Stars 达 1, 最近一次更新时间为 2023 年 02 月 20 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 priteshyadav444/validation 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 priteshyadav444/validation 我们能提供哪些服务?
定制开发 / 二次开发

基于 priteshyadav444/validation 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 8
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 13
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-02-20