定制 martynbiz/php-validator 二次开发

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

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

martynbiz/php-validator

Composer 安装命令:

composer require martynbiz/php-validator

包简介

Basic validation for PHP forms

README 文档

README

##Installation

Install with composer:

composer require martynbiz/php-validator

Basic Usage

$validator = new MartynBiz\Validator();
$validator->setData($_POST);

The check() method instructs the object that this is a new value to validate. Additional methods are chained from this. Below shows an example of the object checking a value is not empty, then checking it is a valid email address.

$validator->check('email')
  ->isNotEmpty('Email address is blank')
  ->isEmail('Invalid email address');

To fetch the errors from a validation check, use getErrors():

$errors = $validator->getErrors();

After validation, check if data is valid:

$continue = $validator->isValid();

Check if a data has been given. Useful for checking checkboxes have been ticked:

$validator->check('name');

Note: will not work for empty strings, which isNonEmpty should also be used.

This will return an array of containing the error that occured (Email address is blank). Please note that although the isEmail method was called too, because it has already gathered an error it does not record another. Remember this when ordering your methods in the chain.

It is also possible to do this in one go, and return errors:

$errors = $validator->check('email')
  ->isNotEmpty('Email address is blank')
  ->isEmail('Invalid email address')
  ->getErrors();

Optional fields are when validation only occurs on that param if the param is given.

$validator->check('age', array('optional' => true))
  ->is...

Other methods for validating

The above example shows how to validate an email address but the following methods can be used to numeric, date and time stings too. Below is the full list of validation methods available.

// strings

$validator->check('name')
  ->isNotEmpty('Value must not be blank');

$validator->check('email')
  ->isEmail('Email address must be valid');

$validator->check('name')
  ->isLetters('Value must be letters');

$validator->check('name')
  ->isMinimumLength('Password must be at least 8 characters', 8);

$validator->check('name')
  ->isMaximumLength('Password must be no more than 16 characters', 16);

// numeric strings

$validator->check('amount')
  ->isNumber('Value must be a number');

$validator->check('profit')
  ->isPositiveNumber('Value must be a positive number');

$validator->check('loss')
  ->isNotPositiveNumber('Value must not be a positive number, negatives and zeros OK');

$validator->check('loss')
  ->isNegativeNumber('Value must be a negative number');

$validator->check('profit')
  ->isNotNegativeNumber('Value must not be a negative number, positives and zeros OK');

// date/time

$validator->check('publish_date')
  ->isDateTime('Value must be date/time format yyyy-mm-dd hh:mm:ss');

$validator->check('publish_date')
  ->isDate('Value must be date format yyyy-mm-dd');

$validator->check('meeting_time')
  ->isTime('Value must be time hh:mm:ss');

// passwords

$message = 'Password must contain upper and lower case characters, and have more than 8 characters';
$validator->check('password')
  ->isNotEmpty($message)
  ->hasLowerCase($message)
  ->hasUpperCase($message)
  ->hasNumber($message)
  ->isMinimumLength($message, 8);

// etc

$validator->check('username')
  ->isNotEmpty('Username missing')
  ->isMaximumLength('Username must not exceed 16 characters', 16);

Other error logging

You can use the logError() method too to log a custom error:

$validator->logError('Could not load api');

Extend Validator

Sometimes it's useful to add your own validator methods. This can be done by extending the class, and ensuring that your new method returns the instance logs the error:

class MyValidator extends Validator
{
    protected $userModel;

    // example constructor with dependency injection
    public function __construct($userModel, $data)
    {
        $this->userModel = $userModel;

        $this->setData($data);
    }

    // create new validation rule
    public function isUniqueEmail($message)
    {
        //check whether this email exists in the db
        //this is an example model, use your own models here
        $user = $this->userModel->findByEmail( $this->value );

        // log error - required
        if ($user) {
          $this->logError($message);
        }

        // return instance - required
        return $this;
    }

    // or create new rule from existing rules
    public function isValidPassword($message)
    {
        return $this
          ->isNotEmpty($message)
          ->hasLowerCase($message)
          ->hasUpperCase($message)
          ->hasNumber($message)
          ->isMinimumLength($message, 8);
    }

    // override isValid so we only have to call this method
    // and keep controllers, etc tidy
    public function isValid()
    {
        // first_name
        $this->check('first_name')
            ->isNotEmpty('First name missing');

        // last_name
        $this->check('last_name')
            ->isNotEmpty('Last name missing');

        $this->check('password')
            ->isValidPassword('Invalid password');

        return parent::isValid();
    }
}

Then you can chain the method as with the built in ones:

$validator = new MyValidator($userModel, $_POST):

if ($validator->isValid()) {
    //..
}

martynbiz/php-validator 适用场景与选型建议

martynbiz/php-validator 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 307 次下载、GitHub Stars 达 0, 最近一次更新时间为 2015 年 10 月 22 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「form」 「validation」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

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

围绕 martynbiz/php-validator 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2015-10-22