crodas/validator 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

crodas/validator

Composer 安装命令:

composer require crodas/validator

包简介

Validation library

README 文档

README

Generate static validators to validate your data in PHP. Static means that the rules are defined offline, then the library generates code to run the validations. We don't run any checking at runtime.

If you need to define validation rules on the fly, for instance you have a CMS or something like that, then this library would be of little help (unless you call the crodas\Validator\Builder manually), in that case I would recommend to take a look at @Respect's validation library which has been an inspiration for this library.

How to installed

The easiest way of install the package is using Composer:

composer "crodas/validator":\*

How to use it

Our object

All the validation rules are defined used Annotatios, it should be like this:

/** @Validate */
class User
{
    /** @Between([18, 99], "Invalid age range, it should be between 18-99") */ 
    protected $age;
    
    /** 
     * @NoWhitespace("Spaces are not allowed")
     * @MinLength([5], "{$value} is too short") 
     * @MaxLength([10], "{$value} is too long")
     */
    public $username;
}

Easy way

You can just call the crodas/Validator/validate function, it will take care of the everything else.

$user = new User;
$user->age = 17;
$user->username = "invalid username";
if (!crodas\Validator\validate($user, $errors)) {
    echo "<h1>There has been an error</h1>";
    foreach ($errors as $property => $error) {
        echo "...\n";
    }
    exit;
}

Hard way

You can also generate the validation object reading the PHP files from a given directory. This project exposes it's engine and compile so this can be done very easily. The first thing you have to do is create the Validator object.

require "vendor/autoload.php";

$val = new crodas\Validator\Init("/classes/", "/tmp/foo.php");

The validator object would look for classes defined inside /classes/ and its subdirectories the first time. It would then load classes with @Validate annotation in it.

To validate an object you would have to do something like this.

$errors = $val->validate(new User);
if (!empty($errors)) {
  foreach ($errors as $field => $exception) {
     echo "{$field} is not valid ( {$exception} )\n";
  }
}

统计信息

  • 总下载量: 2.24k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 1
  • 依赖项目数: 3
  • 推荐数: 0

GitHub 信息

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

其他信息

  • 授权协议: BSD-4-Clause
  • 更新时间: 2013-10-21

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固