nilportugues/validator

PHP的高效数据验证器

3.0.3 2015-11-02 20:28 UTC

This package is not auto-updated.

Last update: 2024-09-14 16:03:19 UTC


README

Build Status Coverage Status Scrutinizer Code Quality SensioLabsInsight Latest Stable Version Total Downloads License Donate

验证是网络应用程序中一个非常常见的任务。表单中输入的数据需要进行验证。在将数据写入数据库或传递给Web服务之前,也需要对数据进行验证。

NilPortugues\Validator是一个简单、强大且优雅的独立验证库,无外部依赖。

  • 1. 安装
  • 2. 使用
  • 3. 验证消息翻译
  • 4. 方法
    • 4.1 isString | 字符串
      • [4.1.1. isAlphanumeric | 阿拉伯数字] (#block4.1.1)
      • [4.1.2. isAlpha | 字母] (#block4.1.2)
      • [4.1.3. isBetween | 之间] (#block4.1.3)
      • [4.1.4. isCharset | 字符集] (#block4.1.4)
      • [4.1.5. isAllConsonants | 全辅音] (#block4.1.5)
      • [4.1.6. contains] (#block4.1.6)
      • [4.1.7. isControlCharacters | 控制字符] (#block4.1.7)
      • [4.1.8. isDigit | 数字] (#block4.1.8)
      • [4.1.9. endsWith | 以...结束] (#block4.1.9)
      • [4.1.10. equals] (#block4.1.10)
      • [4.1.11. in] (#block4.1.11)
      • [4.1.12. hasGraphicalCharsOnly | 只有图形字符] (#block4.1.12)
      • [4.1.13. hasLength | 有长度] (#block4.1.13)
      • [4.1.14. isLowercase | 小写] (#block4.1.14)
      • [4.1.15. notEmpty | 不为空] (#block4.1.15)
      • [4.1.16. noWhitespace | 无空白] (#block4.1.16)
      • [4.1.17. hasPrintableCharsOnly | 只有可打印字符] (#block4.1.17)
      • [4.1.18. isPunctuation | 标点符号] (#block4.1.18)
      • [4.1.19. matchesRegex | 匹配正则表达式] (#block4.1.19)
      • [4.1.20. isSlug | 链接别名] (#block4.1.20)
      • [4.1.21. isSpace | 空格] (#block4.1.21)
      • [4.1.22. startsWith | 以...开始] (#block4.1.22)
      • [4.1.23. isUppercase | 大写] (#block4.1.23)
      • [4.1.24. isVersion | 版本] (#block4.1.24)
      • [4.1.25. isVowel | 元音] (#block4.1.25)
      • [4.1.26. isHexDigit | 十六进制数字] (#block4.1.26)
      • [4.1.27. hasLowercase | 有小写] (#block4.1.27)
      • [4.1.28. hasUppercase | 有大写] (#block4.1.28)
      • [4.1.29. hasNumeric | 有数字] (#block4.1.29)
      • [4.1.30. hasSpecialCharacters | 有特殊字符] (#block4.1.30)
      • [4.1.31. isEmail | 邮箱] (#block4.1.31)
      • [4.1.32. isUrl | URL] (#block4.1.32)
      • [4.1.33. isUUID | UUID] (#block4.1.33)
    • 4.2 isInteger | 整数和 isFloat | 浮点数
      • [4.2.1. isNotZero | 不为零] (#block4.2.1)
      • [4.2.2. isPositive | 正数] (#block4.2.2)
      • [4.2.2. isPositiveOrZero | 非负数] (#block4.2.3)
      • [4.2.4. isNegative | 负数] (#block4.2.4)
      • [4.2.5. isNegativeOrZero | 非正数] (#block4.2.5)
      • [4.2.6. isBetween | 之间] (#block4.2.6)
      • [4.2.7. isOdd | 奇数] (#block4.2.7)
      • [4.2.8. isEven | 偶数] (#block4.2.8)
      • [4.2.9. isMultiple | 是倍数] (#block4.2.9)
    • 4.3 isObject | 对象
      • [4.3.1. isInstanceOf | 是实例] (#block4.3.1)
      • [4.3.2. hasProperty | 有属性] (#block4.3.2)
      • [4.3.3. hasMethod | 有方法] (#block4.3.3)
      • [4.3.4. hasParentClass | 有父类] (#block4.3.4)
      • [4.3.5. isChildOf | 是子类] (#block4.3.5)
      • [4.3.6. inheritsFrom | 继承自] (#block4.3.6)
      • [4.3.7. hasInterface | 有接口] (#block4.3.7)
    • 4.4 isDateTime | 日期时间
      • [4.4.1. isAfter | 之后] (#block4.4.1)
      • [4.4.2. isBefore | 之前] (#block4.4.2)
      • [4.4.3. isBetween | 之间] (#block4.4.3)
      • [4.4.4. isWeekend | 周末] (#block4.4.4)
      • [4.4.5. isWeekday | 工作日] (#block4.4.5)
      • [4.4.6. isMonday | 星期一] (#block4.4.6)
      • [4.4.7. isTuesday | 周二] (#block4.4.7)
      • [4.4.8. isWednesday | 周三] (#block4.4.8)
      • [4.4.9. isThursday | 周四] (#block4.4.9)
      • [4.4.10. isFriday | 周五] (#block4.4.10)
      • [4.4.11. isSaturday | 周六] (#block4.4.11)
      • [4.4.12. isSunday | 周日] (#block4.4.12)
      • [4.4.13. isToday | 今天] (#block4.4.13)
      • [4.4.14. isYesterday | 昨天] (#block4.4.14)
      • [4.4.15. isTomorrow | 明天] (#block4.4.15)
      • [4.4.16. isLeapYear | 是否闰年] (#block4.4.16)
      • [4.4.17. isMorning | 上午] (#block4.4.17)
      • [4.4.18. isAftenoon | 下午] (#block4.4.18)
      • [4.4.19. isEvening | 晚上] (#block4.4.19)
      • [4.4.20. isNight | 夜晚] (#block4.4.20)
    • 4.5 isArray | 数组
      • [4.5.1. each] (#block4.5.1)
      • [4.5.2. hasKeyFormat | has_key_format] (#block4.5.2)
      • [4.5.3. endsWith | ends_with] (#block4.5.3)
      • [4.5.4. contains] (#block4.5.4)
      • [4.5.5. hasKey | has_key] (#block4.5.5)
      • [4.5.6. hasLength | has_length] (#block4.5.6)
      • [4.5.7. isNotEmpty | not_empty] (#block4.5.7)
      • [4.5.8. startsWith | starts_with] (#block4.5.8)
    • 4.6 isFileUpload | 文件上传
      • [4.6.1. isBetween | between] (#block4.6.1)
      • [4.6.2. isMimeType | mime_type] (#block4.6.2)
      • [4.6.3. hasFileNameFormat | has_file_name_format] (#block4.6.3)
      • [4.6.4. hasValidUploadDirectory | has_valid_upload_directory] (#block4.6.4)
      • [4.6.5. notOverwritingExistingFile | not_overwriting_existing_file] (#block4.6.5)
      • [4.6.6. hasLength | has_length] (#block4.6.6)
      • [4.6.7. isImage | image] (#block4.6.7)
  • 4. 质量代码
  • 5. 作者
  • 6. 许可证

1. 安装

推荐通过 Composer 安装 Input Validator。运行以下命令进行安装

php composer.phar require nilportugues/validator

2. 使用

Validator 接口是 100% 适合人类使用和可读的。默认情况下,它支持完全验证和部分验证(在第一个错误发生时停止)。

2.1. 适用于所有人的验证

在编写验证器输入数据时,预期它将匹配一组规则。如果这些规则中的任何一个或多个失败,则返回错误集合。这是 validate($input) 的默认行为。

NilPortugues\Validator 支持最多 3 种不同的编写验证器的风格:实例化、工厂或作为类。以下是针对这 3 种风格验证输入 age 的示例

2.1.1. Validator类的实例化

use \NilPortugues\Validator\Validator;

$ageValidator = Validator::create()->isInteger('age');
$result = $ageValidator->isPositive()->isBetween(18, 100, true)->validate(28);
$errors = $ageValidator->getErrors();

2.1.2. 使用ValidatorFactory::create创建工厂

使用 Validator 作为工厂将在每次使用 ::create 方法时提供 Validator 对象。

当需要逐个验证大量字段或在数组循环内验证时,这种风格最为合适,其中动态更改 $rules 有意义。

use \NilPortugues\Validator\ValidatorFactory;

$rules = ['positive', 'between:18:100:true'];
$ageValidator = ValidatorFactory::create('age', 'integer', $rules);

$result = $ageValidator->validate(28);
$errors = $ageValidator->getErrors();

2.1.3. 从BaseValidator扩展

扩展自 \NilPortugues\Validator\BaseValidator 的验证器简短且易于维护。

use \NilPortugues\Validator\BaseValidator;

class AgeValidator extends BaseValidator
{
    /**
     * @var string
     */
    protected $type = 'integer';

    /**
     * @var array
     */
    protected $rules = [
        'positive',
        'between:18:100:true'
    ];
}

$ageValidator = new AgeValidator();

$result = $ageValidator->validate('age', 28);
$errors = $ageValidator->getErrors();

除非您提供类以进行更改的方法,否则规则不能动态更改!例如

use \NilPortugues\Validator\BaseValidator;

class AgeValidator extends BaseValidator
{
    /**
     * @var string
     */
    protected $type = 'integer';

    /**
     * @var array
     */
    protected $rules = ['positive'];

    /**
     * @param array $rules
     */
    public function __construct(array $rules)
    {
        $this->rules = array_merge($this->rules, $rules);
    }
}

$ageValidator = new AgeValidator(['between:18:100:true']);

$result = $ageValidator->validate('age', 28);
$errors = $ageValidator->getErrors();

2.2. 在第一个错误时停止

在验证输入数据时,有时需要快速的验证检查。通过将 true 作为 validate 方法的第二个参数传递,可以实现这一点。

例如,在以下代码中 isBetween 永远不会执行。

use \NilPortugues\Validator\Validator;

$age = Validator::create()->isInteger('age');
$result = $age->isPositive()->isBetween(0, 100, true)->validate(-10, true);

3. 验证消息翻译

Input Validator 具有默认翻译,可在 src/Errors/en_GB.php 找到。如果创建验证器实例时未提供文件路径,则使用此文件。

Feel free to submit a pull request or open an issue with more translations!

自定义

可以通过提供具有相同结构的文件随时更改语言。

$translationFile = 'full/path/to/alternate-translation.php';

$validator = Validator::create($translationFile);

$stringValidator = $validator->isString('username');
$errors = $stringValidator->getErrors(); //error array in the provided language.

可用翻译

  • en_GB 英语(英国)

4. 方法

所有数据类型验证器共享 2 个基本方法

  • isRequired
  • isNotNull

它的使用非常简单

$validator = Validator::create();

$username = $validator->isString('username');

$username->isRequired()->validate('Nil'); //true
$username->isNotNull()->validate(''); //false

//Or combined...
$username->isRequired()->isNotNull()->validate('Nil'); //true

对于可选数据,使用isset($value)条件包裹验证函数,并使用isNotNull进行验证。

例如,假设性别是一个从0到2的值(男性、女性、其他),并且是一个非必填值

$validator = Validator::create();

$genderValue = $validator->isInteger('gender');
$result = true;

if (isset($gender)) {
    $result = $genderValue->isNotNull()->isBetween(0, 2, true)->validate($gender);
}

return $result;

4.1 字符串 | 字符串

字符串验证是在使用isString方法创建验证器中的字符串字段时开始的。

$username = Validator::create()->isString('username');

以下是一些可用于字符串数据的链式验证选项

4.1.1. isAlphanumeric

4.1.1.1 验证器类的实例化
use \NilPortugues\Validator\Validator;

$string = Validator::create()->isString('propertyName');

$string->isAlphanumeric()->validate('28a'); // true
$string->isAlphanumeric()->validate('hello@example.com'); // false

4.1.1.2. 使用Validator::create创建工厂
use \NilPortugues\Validator\Validator;

$validator = Validator::create('propertyName', 'string', ['alphanumeric']);

$validator->validate('28a'); // true
$validator->validate('hello@example.com'); // false

4.1.1.3. 从BaseValidator扩展
use \NilPortugues\Validator\BaseValidator;

class FieldValidator extends BaseValidator
{
    protected $type = 'string';

    protected $rules = ['alphanumeric'];
}

$fieldValidator = new FieldValidator();

$fieldValidator->validate('propertyName', '28a'); //true
$fieldValidator->validate('propertyName', 'hello@example.com');

4.1.2. isAlpha

示例
$string = Validator::create()->isString('propertyName');

$string->isAlpha()->validate('Hello World'); // true
$string->isAlpha()->validate('28a'); // false
$string->isAlpha()->validate('hello@example.com'); // false

4.1.3. isBetween

示例
$string = Validator::create()->isString('propertyName');

$string->isBetween(2, 4)->validate('Nilo'); //false
$string->isBetween(2, 4, true)->validate('Nilo'); //true

4.1.4. isCharset

示例
$string = Validator::create()->isString('propertyName');

$string->isCharset(['UTF-8'])->validate('Portugués'); //true

4.1.5. isAllConsonants

示例
$string = Validator::create()->isString('propertyName');

$string->isAllConsonants()->validate('a'); //false
$string->isAllConsonants()->validate('bs'); //true

4.1.6. contains

示例
$string = Validator::create()->isString('propertyName');

$string->contains(123)->validate('AAAAAAA123A'); //true
$string->contains(123, true)->validate('AAAAAAA123A'); //false

4.1.7. isControlCharacters

示例
$string = Validator::create()->isString('propertyName');

$string->isControlCharacters()->validate("\n\t"); //true
$string->isControlCharacters()->validate("\nHello\tWorld"); //false

4.1.8. isDigit

示例
$string = Validator::create()->isString('propertyName');

$string->isDigit()->validate('10'); //true

$string->isDigit()->validate('A'); //false
$string->isDigit()->validate(145.6); //false

4.1.9. endsWith

示例
$string = Validator::create()->isString('propertyName');

$string->endsWith('aaaA')->validate('AAAAAAAaaaA'); //true
$string->endsWith(123, true)->validate('AAAAAAA123'); //false

4.1.10. equals

示例
$string = Validator::create()->isString('propertyName');

$string->equals('hello')->validate('hello'); //true

$string->equals(1)->validate('1'); //true
$string->equals(1, true)->validate('1'); //false

4.1.11. in

示例
$string = Validator::create()->isString('propertyName');

$string->in('a12245 asdhsjasd 63-211', true)->validate('5 asd'); //true
$string->in(122, true)->validate('a12245 asdhsjasd 63-211'); //false

4.1.12. hasGraphicalCharsOnly

示例
$string = Validator::create()->isString('propertyName');

$string->hasGraphicalCharsOnly()->validate('arf12'); //true
$string->hasGraphicalCharsOnly()->validate("asdf\n\r\t"); //false

4.1.13. hasLength

示例
$string = Validator::create()->isString('propertyName');

$string->hasLength(5)->validate('abcdefgh'); //false
$string->hasLength(8)->validate('abcdefgh'); //true

4.1.14. isLowercase

示例
$string = Validator::create()->isString('propertyName');

$string->isLowercase()->validate('strtolower'); //true
$string->isLowercase()->validate('strtolOwer'); //false

4.1.15. notEmpty

示例
$string = Validator::create()->isString('propertyName');

$string->notEmpty()->validate('a'); //true
$string->notEmpty()->validate(''); //false

4.1.16. noWhitespace

示例
$string = Validator::create()->isString('propertyName');

$string->noWhitespace()->validate('aaaaa'); //true
$string->noWhitespace()->validate('lorem ipsum'); //false

4.1.17. hasPrintableCharsOnly

示例
$string = Validator::create()->isString('propertyName');

$string->hasPrintableCharsOnly()->validate("LMKA0$%_123"); //true
$string->hasPrintableCharsOnly()->validate("LMKA0$%\t_123"); //false

4.1.18. isPunctuation

示例
$string = Validator::create()->isString('propertyName');

$string->isPunctuation()->validate('&,.;'); //true
$string->isPunctuation()->validate('a'); //false

4.1.19. matchesRegex

示例
$string = Validator::create()->isString('propertyName');

$string->matchesRegex('/[a-z]/')->validate('a'); //true
$string->matchesRegex('/[a-z]/')->validate('A'); //false

4.1.20. isSlug

示例
$string = Validator::create()->isString('propertyName');

$string->isSlug()->validate('hello-world-yeah'); //true

$string->isSlug()->validate('-hello-world-yeah'); //false
$string->isSlug()->validate('hello-world-yeah-'); //false
$string->isSlug()->validate('hello-world----yeah'); //false

4.1.21. isSpace

示例
$string = Validator::create()->isString('propertyName');

$string->isSpace()->validate('    '); //true
$string->isSpace()->validate('e e'); //false

4.1.22. startsWith

示例
$string = Validator::create()->isString('propertyName');

$string->startsWith('aaaA')->validate('aaaAAAAAAAA'); //true
$string->startsWith(123, true)->validate('123AAAAAAA'); //false

4.1.23. isUppercase

示例
$string = Validator::create()->isString('propertyName');

$string->isUppercase()->validate('AAAAAA'); //true
$string->isUppercase()->validate('aaaa'); //false

4.1.24. isVersion

示例
$string = Validator::create()->isString('propertyName');

$string->isVersion()->validate('1.0.2'); //true
$string->isVersion()->validate('1.0.2-beta'); //true
$string->isVersion()->validate('1.0'); //true
$string->isVersion()->validate('1.0.2 beta'); //false

4.1.25. isVowel

示例
$string = Validator::create()->isString('propertyName');

$string->isVowel()->validate('aeA'); //true
$string->isVowel()->validate('cds'); //false

4.1.26. isHexDigit

示例
$string = Validator::create()->isString('propertyName');

$string->isHexDigit()->validate(100); //true
$string->isHexDigit()->validate('h0000'); //false

4.1.27. hasLowercase

示例
$string = Validator::create()->isString('propertyName');

$string->hasLowercase()->validate('HELLOWOrLD'); //true
$string->hasLowercase(3)->validate('HeLLoWOrLD'); //true

$string->hasLowercase()->validate('HELLOWORLD'); //false
$string->hasLowercase(3)->validate('el'); //false

4.1.28. hasUppercase

示例
$string = Validator::create()->isString('propertyName');

$string->hasUppercase()->validate('hello World'); //true
$string->hasUppercase(2)->validate('Hello World'); //true

$string->hasUppercase()->validate('hello world'); //false
$string->hasUppercase(2)->validate('helloWorld'); //false

4.1.29. hasNumeric

示例
$string = Validator::create()->isString('propertyName');

$string->hasNumeric()->validate('hell0 W0rld'); //true
$string->hasNumeric(3)->validate('H3ll0 W0rld'); //true

$string->hasNumeric()->validate('hello world'); //false
$string->hasNumeric(2)->validate('h3lloWorld'); //false

4.1.30. hasSpecialCharacters

示例
$string = Validator::create()->isString('propertyName');

$string->hasSpecialCharacters()->validate('hell0@W0rld'); //true
$string->hasSpecialCharacters(2)->validate('H3ll0@W0@rld'); //true

$string->hasSpecialCharacters()->validate('hello world'); //false
$string->hasSpecialCharacters(2)->validate('h3llo@World'); //false

4.1.31. isEmail

示例
$string = Validator::create()->isString('propertyName');

$string->isEmail()->validate('hello@world.com'); //true
$string->isEmail()->validate('hello.earth@world.com'); //true
$string->isEmail()->validate('hello.earth+moon@world.com'); //true
$string->isEmail()->validate('hello@subdomain.world.com'); //true
$string->isEmail()->validate('hello.earth@subdomain.world.com'); //true
$string->isEmail()->validate('hello.earth+moon@subdomain.world.com'); //true
$string->isEmail()->validate('hello.earth+moon@127.0.0.1'); //true

$string->isEmail()->validate('hello.earth+moon@localhost'); //false

4.1.32. isUrl

示例
$string = Validator::create()->isString('propertyName');

$string->->isUrl()->validate('http://google.com'); //true
$string->->isUrl()->validate('http://google.com/robots.txt'); //true
$string->->isUrl()->validate('https://google.com'); //true
$string->->isUrl()->validate('https://google.com/robots.txt'); //true
$string->->isUrl()->validate('//google.com'); //true
$string->->isUrl()->validate('//google.com/robots.txt'); //true

4.1.33. isUUID($strict = true)

示例
$string = Validator::create()->isString('propertyName');

$string->isUUID()->validate('6ba7b810-9dad-11d1-80b4-00c04fd430c8'); //true
$string->isUUID()->validate('6ba7b811-9dad-11d1-80b4-00c04fd430c8'); //true
$string->isUUID()->validate('6ba7b812-9dad-11d1-80b4-00c04fd430c8'); //true
$string->isUUID()->validate('6ba7b814-9dad-11d1-80b4-00c04fd430c8'); //true
$string->isUUID()->validate('00000000-0000-0000-0000-000000000000'); //true

$string->isUUID(false)->validate('6ba7b810-9dad-11d1-80b4-00c04fd430c8'); //true
$string->isUUID(false)->validate('6ba7b811-9dad-11d1-80b4-00c04fd430c8'); //true
$string->isUUID(false)->validate('6ba7b812-9dad-11d1-80b4-00c04fd430c8'); //true
$string->isUUID(false)->validate('6ba7b814-9dad-11d1-80b4-00c04fd430c8'); //true
$string->isUUID(false)->validate('00000000-0000-0000-0000-000000000000'); //true

$string->isUUID()->validate('{6ba7b810-9dad-11d1-80b4-00c04fd430c8}'); //false
$string->isUUID()->validate('216f-ff40-98d9-11e3-a5e2-0800-200c-9a66'); //false
$string->isUUID()->validate('{216fff40-98d9-11e3-a5e2-0800200c9a66}'); //false
$string->isUUID()->validate('216fff4098d911e3a5e20800200c9a66'); //false

$string->isUUID(false)->validate('{6ba7b810-9dad-11d1-80b4-00c04fd430c8}'); //true
$string->isUUID(false)->validate('216f-ff40-98d9-11e3-a5e2-0800-200c-9a66'); //true
$string->isUUID(false)->validate('{216fff40-98d9-11e3-a5e2-0800200c9a66}'); //true
$string->isUUID(false)->validate('216fff4098d911e3a5e20800200c9a66'); //true

4.2 isInteger | 整数和 isFloat | 浮点数

数字验证有两种形式,即 IntegersFloats。这两种验证器具有相同的方法接口,但内部实现不同。

要使用这些验证器,请按照以下步骤操作

$integer = Validator::create()->isInteger('propertyName');

$float = $validator->isFloat('propertyName');

4.2.1. isNotZero

示例
$integer = Validator::create()->isInteger('propertyName');

$integer->isNotZero()->validate(1); //true
$integer->isNotZero()->validate(0); //false

4.2.2. isPositive

示例
$integer = Validator::create()->isInteger('propertyName');

$integer->isPositive()->validate(1); //true
$integer->isPositive()->validate(-10); //false
$integer->isPositive()->validate(0); //false

4.2.3. isPositiveOrZero

示例
$integer = Validator::create()->isInteger('propertyName');

$integer->isPositiveOrZero()->validate(1); //true
$integer->isPositiveOrZero()->validate(-10); //false
$integer->isPositiveOrZero()->validate(0); //true

4.2.4. isNegative

示例
$integer = Validator::create()->isInteger('propertyName');

$integer->isNegative()->validate(-10); //true
$integer->isNegative()->validate(1); //false
$integer->isNegative()->validate(0); //false

4.2.5. isNegativeOrZero

示例
$integer = Validator::create()->isInteger('propertyName');

$integer->isNegativeOrZero()->validate(-10); //true
$integer->isNegativeOrZero()->validate(1); //false
$integer->isNegativeOrZero()->validate(0); //true

4.2.6. isBetween

示例
$integer = Validator::create()->isInteger('propertyName');

$integer->isBetween(10,20, false)->validate(13); //true
$integer->isBetween(10, 20, true)->validate(10); //false

4.2.7. isOdd

示例
$integer = Validator::create()->isInteger('propertyName');

$integer->isOdd()->validate(3); //true
$integer->isOdd()->validate(2); //false

4.2.8. isEven

示例
$integer = Validator::create()->isInteger('propertyName');

$integer->isEven()->validate(2); //true
$integer->isEven()->validate(3); //false

4.2.9. isMultiple

示例
$integer = Validator::create()->isInteger('propertyName');

$integer->isMultiple(2)->validate(4); //true
$integer->isMultiple(2)->validate(3); //false

4.3 isObject | 对象

4.3.1. isInstanceOf

示例
$object = Validator::create()->isObject('propertyName');

$object->isInstanceOf('DateTime')->validate(new \DateTime()); //true

$object->isInstanceOf('DateTime')->validate(new \stdClass()); //false
$object->isInstanceOf('DateTime')->validate('a'); //false

4.3.2. hasProperty

示例
$object = Validator::create()->isObject('propertyName');

$dummy = new Dummy();

$object->hasProperty('userName')->validate($dummy); //true
$object->hasProperty('password')->validate($dummy); //false

4.3.3. hasMethod

示例
$object = Validator::create()->isObject('propertyName');

$dummy = new Dummy();

$object->hasMethod('getUserName')->validate($dummy); //true
$object->hasMethod('getPassword')->validate($dummy); //false

4.3.4. hasParentClass

示例
$object = Validator::create()->isObject('propertyName');

$object->hasParentClass()->validate(new Dummy()); //true
$object->hasParentClass()->validate(new \stdClass()); //false

4.3.5. isChildOf

示例
$object = Validator::create()->isObject('propertyName');

$dummy = new Dummy(); // class Dummy extends \DateTime

$object->isChildOf('DateTime')->validate($dummy); //true
$object->isChildOf('DateTimeZone')->validate($dummy); //false

4.3.6. inheritsFrom

示例
$object = Validator::create()->isObject('propertyName');

$dummy = new Dummy(); // class Dummy extends \DateTime

$object->inheritsFrom('DateTime')->validate($dummy); //true
$object->inheritsFrom('DateTimeZone')->validate($dummy); //false

4.3.7. hasInterface

示例
$object = Validator::create()->isObject('propertyName');

$object->hasInterface('Tests\NilPortugues\Validator\Resources\DummyInterface')->validate($dummy); //true
$object->inheritsFrom('DateTimeZone')->validate($dummy); //false

4.4 isDateTime | 日期时间

日期时间验证器接受表示有效日期格式的 \DateTime 对象和 strings 变量。

以下示例将说明,对于任何 date 值,允许使用两个参数。

4.4.1. isAfter

示例
$datetime = Validator::create()->isDateTime('propertyName');
$date1 = '2014-01-01 00:00:00';
$date2 = new \DateTime($date1);

$limit1 = '2013-12-31 23:59:59';

$datetime->isAfter($limit1, false)->validate($date1); // true
$datetime->isAfter($limit1, false)->validate($date2); // true

$datetime->isAfter($date1, true)->validate($date1); // true
$datetime->isAfter($date2, true)->validate($date2); // true

$limit2 = '2015-01-01 00:00:00';

$datetime->isAfter($limit2)->validate($date1); // false
$datetime->isAfter($limit2)->validate($date2); // false

4.4.2. isBefore

示例
$datetime = Validator::create()->isDateTime('propertyName');
$date1 = '2012-01-01 00:00:00';
$date2 = new \DateTime($date1);

$limit1 = '2013-12-31 23:59:59';

$datetime->isBefore($limit1, false)->validate($date1); // true
$datetime->isBefore($limit1, false)->validate($date2); // true

$datetime->isBefore($date1, true)->validate($date1); // true
$datetime->isBefore($date2, true)->validate($date2); // true

$limit2 = '2010-01-01 00:00:00';

$datetime->isBefore($limit2)->validate($date1); // false
$datetime->isBefore($limit2)->validate($date2); // false

4.4.3. isBetween

示例
$datetime = Validator::create()->isDateTime('propertyName');
$date1 = '2014-01-01 00:00:00';
$date2 = new \DateTime($date1);

$minDate = '2013-01-01 00:00:00';
$maxDate = '2015-01-01 00:00:00';

$datetime->isBetween($minDate, $maxDate, false)->validate($date1); // true
$datetime->isBetween($minDate, $maxDate, false)->validate($date2); // true

$datetime->isBetween($minDate, $maxDate, true)->validate($date1); // true
$datetime->isBetween($minDate, $maxDate, true)->validate($date2); // true

$minDate = '2013-12-01 00:00:00';
$maxDate = '2013-12-30 00:00:00';

$datetime->isBetween($minDate, $maxDate, false)->validate($date1); // false
$datetime->isBetween($minDate, $maxDate, true)->validate($date1); // false

4.4.4. isWeekend

示例
$datetime = Validator::create()->isDateTime('propertyName');

$datetime->isWeekend()->validate('2014-09-20'); // true
$datetime->isWeekend()->validate('2014-09-22'); // false

4.4.5. isWeekday

示例
$datetime = Validator::create()->isDateTime('propertyName');

$datetime->isWeekday()->validate('2014-09-20'); // false
$datetime->isWeekday()->validate('2014-09-22'); // true

4.4.6. isMonday

示例
$datetime = Validator::create()->isDateTime('propertyName');

$datetime->isMonday()->validate('2014-09-22'); // true

4.4.7. isTuesday

示例
$datetime = Validator::create()->isDateTime('propertyName');

$datetime->isTuesday()->validate('2014-09-23'); // true

4.4.8. isWednesday

示例
$validator = Validator::create();
$datetime = $validator->isDateTime('propertyName');

$datetime->isWednesday()->validate('2014-09-24'); // true

4.4.9. isThursday

示例
$datetime = Validator::create()->isDateTime('propertyName');

$datetime->isThursday()->validate('2014-09-25'); // true

4.4.10. isFriday

示例
$datetime = Validator::create()->isDateTime('propertyName');

$datetime->isFriday()->validate('2014-09-26'); // true

4.4.11. isSaturday

示例
$datetime = Validator::create()->isDateTime('propertyName');

$datetime->isSaturday()->validate('2014-09-27'); // true

4.4.12. isSunday

示例
$datetime = Validator::create()->isDateTime('propertyName');

$datetime->isSunday()->validate('2014-09-28'); // true

4.4.13. isToday

示例
$datetime = Validator::create()->isDateTime('propertyName');

$date = new \DateTime('now');

$datetime->isToday()->validate($date); // true

4.4.14. isYesterday

示例
$datetime = Validator::create()->isDateTime('propertyName');

$date = new \DateTime('now -1 day');

$datetime->isYesterday()->validate($date); // true

4.4.15. isTomorrow

示例
$datetime = Validator::create()->isDateTime('propertyName');

$date = new \DateTime('now +1 day');

$datetime->isTomorrow()->validate($date); // true

4.4.16. isLeapYear

示例
$datetime = Validator::create()->isDateTime('propertyName');

$date = new \DateTime('2016-01-01');

$datetime->isLeapYear()->validate($date); // true

4.4.17. isMorning

示例
$datetime = Validator::create()->isDateTime('propertyName');

4.4.18. isAftenoon

示例
$datetime = Validator::create()->isDateTime('propertyName');

4.4.19. isEvening

示例
$datetime = Validator::create()->isDateTime('propertyName');

4.4.20. isNight

示例
$datetime = Validator::create()->isDateTime('propertyName');

4.5 isArray | array

集合是包含其他数据结构或同一类型变量的数据结构。

集合验证器支持的PHP数据结构包括

  • 数组
  • ArrayObject
  • SplFixedArray

4.5.1. each

示例
$validator = Validator::create();
$collection = $validator->isArray('propertyName');

$valueIsString = $validator->isString('value')->isAlpha();
$keyIsInteger = $validator->isInteger('key')->isPositive();

$array = ['hello','world'];
$arrayObject = new \ArrayObject($array);
$fixedArray = (new \SplFixedArray())->fromArray($array);

$collection->each($valueIsString)->validate($array); //true
$collection->each($valueIsString, $keyIsInteger)->validate($array); //true

$collection->each($valueIsString)->validate($arrayObject); //true
$collection->each($valueIsString, $keyIsInteger)->validate($arrayObject); //true

$collection->each($valueIsString)->validate($fixedArray); //true
$collection->each($valueIsString, $keyIsInteger)->validate($fixedArray); //true

4.5.2. hasKeyFormat

示例
$validator = Validator::create();
$collection = $validator->isArray('propertyName');

$array = ['one' => 'hello', 'two' => 'world'];
$arrayObject = new \ArrayObject($array);
$fixedArray = (new \SplFixedArray())->fromArray(array_values($array));

$keyIsString = $validator->isString('key')->isAlpha();
$keyIsInteger = $validator->isInteger('key')->isPositive();

$collection->hasKeyFormat($keyIsString)->validate($array); //true
$collection->hasKeyFormat($keyIsString)->validate($arrayObject); //true
$collection->hasKeyFormat($keyIsInteger)->validate($fixedArray); //true

4.5.3. endsWith

示例
$collection = Validator::create()->isArray('propertyName');

$array = ['one' => 'hello', 'two' => 1];
$arrayObject = new \ArrayObject($array);
$fixedArray = (new \SplFixedArray())->fromArray(array_values($array));

$collection->endsWith('1')->validate($array); //true
$collection->endsWith('1')->validate($arrayObject); //true
$collection->endsWith('1')->validate($fixedArray); //true

$collection->endsWith('1', true)->validate($array); //false
$collection->endsWith('1', true)->validate($arrayObject); //false
$collection->endsWith('1', true)->validate($fixedArray); //false

4.5.4. contains

示例
$collection = Validator::create()->isArray('propertyName');

$array = ['one' => 'hello', 'two' => 1];
$arrayObject = new \ArrayObject($array);
$fixedArray = (new \SplFixedArray())->fromArray(array_values($array));

$collection->contains('hello')->validate($array); //true
$collection->contains('hello')->validate($arrayObject); //true
$collection->contains('hello')->validate($fixedArray); //true

$collection->contains(1, true)->validate($array); //true
$collection->contains(1, true)->validate($arrayObject); //true
$collection->contains(1, true)->validate($fixedArray); //true

4.5.5. hasKey

示例
$collection = Validator::create()->isArray('propertyName');

$array = ['one' => 'hello', 'two' => 1];
$arrayObject = new \ArrayObject($array);
$fixedArray = (new \SplFixedArray())->fromArray(array_values($array));

$collection->hasKey('one')->validate($array)); //true
$collection->hasKey('one')->validate($arrayObject)); //true
$collection->hasKey(0)->validate($fixedArray)); //true

$array = [];
$arrayObject = new \ArrayObject($array);
$fixedArray = (new \SplFixedArray())->fromArray(array_values($array));

$collection->hasKey(0)->validate($array)); //false
$collection->hasKey(0)->validate($arrayObject)); //false
$collection->hasKey(0)->validate($fixedArray)); //false

4.5.6. hasLength

示例
$collection = Validator::create()->isArray('propertyName');

$array = ['one' => 'hello', 'two' => 1];
$arrayObject = new \ArrayObject($array);
$fixedArray = (new \SplFixedArray())->fromArray(array_values($array));

$collection->hasLength(2)->validate($array)); //true
$collection->hasLength(2)->validate($arrayObject)); //true
$collection->hasLength(2)->validate($fixedArray)); //true

$array = [];
$arrayObject = new \ArrayObject($array);
$fixedArray = (new \SplFixedArray())->fromArray(array_values($array));

$collection->hasLength(0)->validate($array)); //true
$collection->hasLength(0)->validate($arrayObject)); //true
$collection->hasLength(0)->validate($fixedArray)); //true

4.5.7. isNotEmpty

示例
$collection = Validator::create()->isArray('propertyName');

$array = ['one' => 'hello', 'two' => 1];
$arrayObject = new \ArrayObject($array);
$fixedArray = (new \SplFixedArray())->fromArray(array_values($array));

$collection->isNotEmpty()->validate($array)); //true
$collection->isNotEmpty()->validate($arrayObject)); //true
$collection->isNotEmpty()->validate($fixedArray)); //true

$array = [];
$arrayObject = new \ArrayObject($array);
$fixedArray = (new \SplFixedArray())->fromArray(array_values($array));

$collection->isNotEmpty()->validate($array)); //false
$collection->isNotEmpty()->validate($arrayObject)); //false
$collection->isNotEmpty()->validate($fixedArray)); //false

4.5.8. startsWith

示例
$collection = Validator::create()->isArray('propertyName');

$array = [1, 2, 3];
$arrayObject = new \ArrayObject($array);
$fixedArray = (new \SplFixedArray())->fromArray($array);

$collection->startsWith(1)->validate($array)); //true
$collection->startsWith(1)->validate($arrayObject)); //true
$collection->startsWith(1)->validate($fixedArray)); //true

$collection->startsWith('1', true)->validate($array)); //false
$collection->startsWith('1', true)->validate($arrayObject)); //false
$collection->startsWith('1', true)->validate($fixedArray)); //false

4.6 isFileUpload | file_upload

文件上传验证是Web开发中最枯燥的部分之一,但这个验证器让事情变得简单。

一个文件验证

仅使用FileUpload验证器,您就可以验证单个文件上传。

<form method="POST" enctype="multipart/form-data">
  <input name="image" type="file" accept="image/*">
  <input type="submit" value="Submit">
</form>

在服务器端,验证如下进行

$fileValidator = Validator::create()->isFileUpload('image');

$fileValidator
     ->isBetween(0, 3, 'MB', true)
     ->isMimeType(['image/png', 'image/gif', 'image/jpeg'])
     ->hasValidUploadDirectory('./uploads/images')
     ->notOverwritingExistingFile('./uploads/images')
     ->validate('image');

多个文件验证

例如,假设文件上传是通过以下表单完成的

<form method="POST" enctype="multipart/form-data">
  <input type="file" name="image[]" multiple="multiple" accept="image/*">
  <input type="submit" value="Submit">
</form>

在服务器端与之前完全相同!简单,对吧? :)

4.6.1. isBetween($minSize, $maxSize, $inclusive = false)

示例
$file = Validator::create()->isFileUpload('image');

$file->isBetween(1, 3, 'MB', true)->validate('image');

4.6.2. isMimeType(array $allowedTypes)

示例
$file = Validator::create()->isFileUpload('image');

$file->isMimeType(['image/png', 'image/gif', 'image/jpeg'])->validate('image');

4.6.3. hasFileNameFormat(AbstractValidator $validator)

示例
$validator = Validator::create();
$file = $validator->isFileUpload('image');
$stringValidator = $validator->isString('image')->isAlpha();

$file->hasFileNameFormat($stringValidator)->validate('image');

4.6.4. hasValidUploadDirectory($uploadDir)

示例
$file = Validator::create()->isFileUpload('image');

$file->hasValidUploadDirectory('./uploads/images')->validate('image');

4.6.5. notOverwritingExistingFile($uploadDir)

示例
$file = Validator::create()->isFileUpload('image');

$file->notOverwritingExistingFile('./uploads/images')->validate('image');

4.6.6. hasLength($size)

示例
$file = Validator::create()->isFileUpload('image');

$file->hasLength(1)->validate('image');

4.6.7. isImage()

示例
$file = Validator::create()->isFileUpload('image');

$file->isImage()->validate('image');

4. 质量代码

测试已使用PHPUnit和Travis-CI进行。所有代码都已测试,确保与PHP 5.4至PHP 5.6和HHVM兼容。

要运行测试套件,您需要Composer

    php composer.phar install --dev
    php bin/phpunit

5. 作者

Nil Portugués Calderó

6. 许可证

输入验证器遵循MIT许可证。