syncxplus/php-validation

此包已被废弃,不再维护。未建议替代包。
此包最新版本(1.0.0)的许可证信息不可用。

源自 blackbelt/php-validation

1.0.0 2016-04-07 02:57 UTC

This package is not auto-updated.

Last update: 2020-08-13 23:38:14 UTC


README

此类遵循Zend Framework的命名约定,便于作为Zend_Validation的替代品直接使用。如果您不想在项目中使用体积庞大的Zend_Form,可以选择使用这个库来进行快速且简便的表单验证。

快速示例

以下示例展示了如何使用自定义异常抛出验证异常。然后您可以从调用方法中检索错误信息。在控制器中验证数据不是良好的实践,这应该在模型中处理。这只是一个快速示例。

<?php
class ExampleController extends Zend_Controller_Action {

    /**
     * Your controller action that handles validation errors, as you would
     * want these errors passed on to the view.
     *
     * @access  public
     * @return  void
     */
    public function indexAction()
    {
        try {

            // validate the data
            $validData = $this->_validate($_POST);

            // validation passed because no exception was thrown
            // ... to something with the $validData ...

        } catch (Validator_Exception $e) {
            // retrieve the overall error message to display
            $message = $e->getMessage();

            // retrieve all of the errors
            $errors = $e->getErrors();

            // the below code is specific to ZF
            $this->_helper->FlashMessenger(array('error' => $message));
            $this->_helper->layout->getView()->errors = $errors;
        }
    }

    /**
     * Your user-defined validation handling. The exception section is
     * very important and should always be used.
     *
     * @access  private
     * @param   array   $post
     * @return  mixed
     */
    private function _validate(array $post = array())
    {
        $validator = new Validator($post);
        $validator
            ->required('You must supply a name.')
            ->validate('name', 'Name');
        $validator
            ->required('You must supply an email address.')
            ->email('You must supply a valid email address')
            ->validate('email', 'Email');

        // check for errors
        if ($validator->hasErrors()) {
            throw new Validator_Exception(
                'There were errors in your form.',
                $validator->getAllErrors()
            );
        }

        return $validator->getValidData();
    }

}

可用的验证方法

  • required($message = null) - 字段值是必需的。
  • email($message = null) - 字段值必须是一个有效的电子邮件地址字符串。
  • float($message = null) - 字段值必须是一个浮点数。
  • integer($message = null) - 字段值必须是一个整数。
  • digits($message = null) - 字段值必须是一个数字(无上限的整数)。
  • min($limit, $include = TRUE, $message = null) - 字段值必须大于$limit(数字)。$include定义值是否可以等于限制。
  • max($limit, $include = TRUE, $message = null) - 字段值必须小于$limit(数字)。$include定义值是否可以等于限制。
  • between($min, $max, $include = TRUE, $message = null) - 字段值必须在$min和$max(数字)之间。$include定义值是否可以等于$min和$max。
  • minLength($length, $message = null) - 字段值必须大于或等于$length个字符。
  • maxLength($length, $message = null) - 字段值必须小于或等于$length个字符。
  • length($length, $message = null) - 字段必须恰好是$length个字符长。
  • matches($field, $label, $message = null) - 一个字段与另一个字段匹配(例如密码匹配)
  • notMatches($field, $label, $message = null) - 字段值必须不匹配$field的值。
  • startsWith($sub, $message = null) - 字段必须以字符串$sub开头。
  • notStartsWith($sub, $message = null) - 字段必须不以字符串$sub开头。
  • endsWith($sub, $message = null) - 字段必须以字符串$sub结尾。
  • notEndsWith($sub, $message = null) - 字段必须不以字符串$sub结尾。
  • ip($message = null) - 字段值是一个有效的IP,使用filter_var确定。
  • url($message = null) - 字段值是一个有效的URL,使用filter_var确定。
  • date($message = null) - 字段值是一个有效的日期,可以是DateTime()接受的任何格式。
  • minDate($date, $format, $message = null) - 日期必须大于 $date。$format 必须是页面 https://php.ac.cn/manual/en/datetime.createfromformat.php 上的格式。
  • maxDate($date, $format, $message = null) - 日期必须小于 $date。$format 必须是页面 https://php.ac.cn/manual/en/datetime.createfromformat.php 上的格式。
  • ccnum($message = null) - 字段值必须是有效的信用卡号。
  • oneOf($allowed, $message = null) - 字段值必须是 $allowed 中的其中一个值。$allowed 可以是一个数组或者以逗号分隔的值列表。如果是逗号分隔的,除非有意进行匹配,否则不要包含空格。
  • callback($callback, $message = '', $params = array()) - 定义自己的自定义回调验证函数。$callback 必须通过 is_callable() 检查。$params 可以是任何值,或者一个数组,如果需要传递多个参数。

回调示例

回调函数可以作为字符串或闭包传递。

// numeric example
$validadator
  ->callback('is_numeric', 'Field is not numeric.')
  ->validate('number_field');

// closure example
$validator
  ->callback(function($val) {
    return $val < -1 || $val > 1;
  }, 'Number must be less than -1 or greater than 1.')
  ->validate('number_field_2');

验证数组和数组索引

此验证类已扩展,允许验证数组以及多维数组的嵌套索引。

验证特定索引

要验证数组的特定索引,请使用点表示法,例如。

<?php
// load the validator
$validator = new Validator($_POST);

// ensure $_POST['field']['nested'] exists
$validator
  ->required('The nested field is required.')
  ->validate('field.nested');

// ensure we have the first two numeric indices of $_POST['links'][]
$validator
  ->required('This field is required')
  ->validate('links.0');
$validator
  ->required('This field is required')
  ->validate('links.1');

可用的预验证过滤

您可以对数据进行预验证过滤(例如 trim, strip_tags, htmlentities)。这些过滤器也可以自定义,只要它们通过 is_callable() 检查即可。

  • filter($callback)

过滤示例

    // standard php filter for valid user ids.
    $validator
      ->filter('intval')
      ->min(1)
      ->validate('user_id');

    // custom filter
    $validator
      ->filter(function($val) {
        // bogus formatting of the field
        $val = rtrim($val, '/');
        $val .= '_custom_formatted';
        return $val;
      })
      ->validate('field_to_be_formatted');

致谢

许可

版权所有 (c) 2012 http://github.com/bekos, http://github.com/blackbe.lt

特此授予任何获得此软件及其相关文档副本(以下简称“软件”)的人免费使用权,包括但不限于使用、复制、修改、合并、发布、分发、再许可和/或销售软件副本,并允许软件的接受者进行上述行为,前提是

上述版权声明和本许可声明应包含在软件的所有副本或主要部分中。

本软件按“原样”提供,不提供任何形式的保证,无论是明示的还是暗示的,包括但不限于对适销性、特定用途适用性和非侵权的保证。在任何情况下,作者或版权所有者均不对任何索赔、损害或其他责任承担责任,无论这些责任是由于合同、侵权或其他原因,是否与软件或软件的使用或其他方式有关。