Home  >  Article  >  Backend Development  >  Yii core validator api detailed explanation_php example

Yii core validator api detailed explanation_php example

WBOY
WBOYOriginal
2016-12-05 13:28:251070browse

This article describes the Yii core validator API with examples. Share it with everyone for your reference, the details are as follows:

Core Validators

Foreword

Yii provides a series of commonly used core validators, which you can find in
Found in the yiivalidators namespace. Instead of using long validator class names, you can use aliases instead of them.

For example, you can use the alias required instead of the yiivalidatorsRequiredValidator class:

<&#63;php
public function rules()
{
  return [
    [['email', 'password'], 'required'],
  ];
}
&#63;>

The yiivalidatorsValidator::$builtInValidators property gives aliases to all supported validators.

Next, we will explain the usage of each core validator.

1. boolean true or false value

<&#63;php
[
  // 检查是否 "selected" 是 0 或 1, 不管数据类型
  ['selected', 'boolean'],
  // 检查是否 "deleted" 是一个 boolean 类型, 只能是 true 或则 false
  ['deleted', 'boolean', 'trueValue' => true, 'falseValue' => false, 'strict' => true],
]
&#63;>

The above detects whether it is a bool value.

trueValue: represents the value when true. The default is '1'.
falseValue: represents the value when false. The default is '0'.
strict: Whether the value in the input box must match the set trueValue and falseValue. The default is false.

Note: Because the data submitted through HTML is character-based, generally you need to set the strict attribute to false.

2. captcha verification code

<&#63;php
[
  ['verificationCode', 'captcha'],
]
&#63;>

This validator is usually the same as
yiicaptchaCaptchaAction and
Use together with yiicaptchaCaptcha to ensure that the same captcha is entered via the CAPTCHA component.
caseSensitive: Whether the verification code needs to be case sensitive. The default is false.
captchaAction: The default CAPTCHA action of the verification code generates the path of the CAPTCHA image. The default is 'site/captcha'.
skipOnEmpty: Whether to skip verification when the input is empty. The default is false, that is, input input is required.

3. compare compare

<&#63;php
[
  // 验证是否 "password" 属性和 "password_repeat"是否相等
  ['password', 'compare'],
  // 验证 age >= 30
  ['age', 'compare', 'compareValue' => 30, 'operator' => '>='],
]
&#63;>

This validator compares the specified input value to another value ensuring that the specified operator is used between them.

compareAttribute: With whom the attribute name will be compared. When the validator is used to verify an attribute, it will be compared with an attribute with the same attribute name but with the suffix _repeat. For example, if the attribute to be verified The name is password, then the default attribute name for comparison is password_repeat. You can specify the value you want.
compareValue: A constant value compared with the input value. When the property and compareAttribute attributes are specified at the same time, this value will take precedence.
operator: Comparison operator. The default is ==, that is, it will succeed only when the input value is equal to the compareAttribute or compareValue value.
The following operators are supported: ==, ===, !=, !==, >, >=, bc24f5e4f67a1e8ecf56798247d6f391formatter->dateFormat.
timestampAttribute: The attribute name used to store the date or time that the transformation will input. It can also be the same attribute name as the one being validated. If this is the case, the original value will be overwritten with the timestamp. You can see See "How to handle date picker DatePicker" for examples.
http://www.yiiframework.com/doc-2.0/widget-jui#datepicker-date-input

If the input is optional, you may also want to add a default value filter in addition to the date validation to ensure that empty inputs are stored as NULL. Otherwise you might end up with dates like 0000-00-00 in the date picker's input field or 1970-01-01 in your database.

<&#63;php
[
  [['from_date', 'to_date'], 'default', 'value' => null],
  [['from_date', 'to_date'], 'date'],
],
&#63;>

5.default default value

<&#63;php
[
  // 设置 "age" 为 null 如果他是空的
  ['age', 'default', 'value' => null],
  // 设置 "country" 为 "USA" 如果他是空的
  ['country', 'default', 'value' => 'USA'],
  // 分配 "from" 和 "to" 分别加3天和6天, 如果他们是空的话
  [['from', 'to'], 'default', 'value' => function ($model, $attribute) {
    return date('Y-m-d', strtotime($attribute === 'to' &#63; '+3 days' : '+6 days'));
  }],
]
&#63;>

This validator does not validate data. Assign to attribute values ​​when they are empty.

value: The default value of the form. The function prototype is as follows,

<&#63;php
function foo($model, $attribute) {
  // ... 组装 $value ...
  return $value;
}
&#63;>

6. double floating point value

<&#63;php
[
  // 检查 "salary" 是一个 double 数字
  ['salary', 'double'],
]
&#63;>

Equivalent to a number validator:

max: The upper limit of the number, it will not be checked if it is not set
min: Number is offline, no setting or checking

7. Email verification

<&#63;php
[
  // 检查邮箱是一个有效的 "email"地址
  ['email', 'email'],
]
&#63;>

allowName: 检查名字是否允许在邮箱中出现 (e.g. John Smith ab332fd52cc796cdb46e8762a080788c). 默认为 false.
checkDNS,是否检查电子邮件的域名是否存在,是否有任何一个A或MX记录。请注意,这可能检查由于临时DNS问题失败,即使电子邮件地址实际上是有效的。默认为false。
enableIDN,验证过程是否应考虑到IDN(国际化域名)。默认为false。需要注意的是,为了使用IDN验证您必须安装并启用国际PHP扩展,或异常将被抛出。

8. exist 是否存在

<&#63;php
[
  // a1 需要在 属性列中存在 "a1" 这个好像默认就有啊
  ['a1', 'exist'],
  // a1 存在,但它的值将使用A2来检查是否存在
  ['a1', 'exist', 'targetAttribute' => 'a2'],
  // a1 和 a2 需要同时存在, 他们都将接收错误信息
  [['a1', 'a2'], 'exist', 'targetAttribute' => ['a1', 'a2']],
  // a1 和 a2 需要同时存在, 只有 a1 将接收错误信息
  ['a1', 'exist', 'targetAttribute' => ['a1', 'a2']],
  // a1 需要存在 通过检测a2 和 a3 (用 a1 的值)
  ['a1', 'exist', 'targetAttribute' => ['a2', 'a1' => 'a3']],
  // a1 需要存在. 如果 a1是一个数组, 那么每个元素都必须存在.
  ['a1', 'exist', 'allowArray' => true],
]
&#63;>

这个验证器检查输入的值能否被找到在在对应的表的列值里,他只会在 Active Record model 模型的属性里起作用.

他支持验证单列或多列

targetClass: 用来寻找输入值验证的 Active Record 类名. 如果未设置, 默认使用当前设置的模型类.
targetAttribute: 应该用于验证输入值的存在在targetClass的属性的名称。如果没有设置,将使用目前正在验证的属性的名称。可以使用阵列来验证多列的存在的同时。数组的值是将被用于验证存在的属性,而数组键是其值要验证的属性。如果键和值都是一样的,你可以指定值.
filter: additional filter to be applied to the DB query used to check the existence of the input value. This can be a string or an array representing the additional query condition (refer to yii\db\Query::where() on the format of query condition), or an anonymous function with the signature function ($query), where $query is the Query object that you can modify in the function.
allowArray: 是否允许输入的值是一个array.默认 false. 若果属性是 true 而且输入是一个 array, 那么熟这里的每一个元素都必须存在在指向的目标列里. 注意这个属性不能被设置成true 如果你设置验证多列通过设置 targetAttribute 为一个 array.

9. file 文件验证

<&#63;php
[
  // 检查 "primaryImage" 上传的文件格式是 PNG, JPG 或者 GIF
  // the file size must be less than 1MB
  ['primaryImage', 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 1024*1024],
]
&#63;>

检查是否是一个有效的上传文件。

extensions: 允许上传的文件类型列表.他可以是一个数组 或者是一个以逗号分割的字符串(如. "gif, jpg"). 扩展名不区分大小写,默认为 null, 意味着所有的文件扩展名是允许的.
mimeTypes: 允许上传的文件资源的媒体类型。他可以是一个数组 或者是一个以逗号或空格分割的字符串 (如. "image/jpeg, image/png"). 不区分大小写,默认为 null, 意味着所有的文件扩展名是允许的.
minSize: 上传文件的最小字节数 未设不做判断.
maxSize: 上传文件的最大字节数 未设不做判断.
maxFiles: 最大的上传文件数 默认为 1, 意味着只能上传单个文件对于单个文件上传框. 如果大于 1, 那么 input必须是一个 array 包含至多 maxFiles 数量的上传文件.
checkExtensionByMimeType: 是否检查文件的扩展名. 如果由MIME类型检查所产生的扩展不同于上传的文件扩展名,该文件将被认为是无效的。默认值为true,意思进行这样的检查。
FileValidator 和 yii\web\UploadedFile 一起使用. .

文件上传请参考:http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html

10. filter 过滤

<&#63;php
[
  // 去掉 "username" 和 "email" 输入空格 跳过数组验证
  [['username', 'email'], 'filter', 'filter' => 'trim', 'skipOnArray' => true],
  // 验证正常 "phone" 输入
  ['phone', 'filter', 'filter' => function ($value) {
    // 验证正确性手机代码
    return $value;
  }],
]
&#63;>

这个验证器验证不了数据. 相反的, it applies a filter on the input value and assigns it back to the attribute being validated.

filter: 一个php回调函数定义一个filter. 他可能是一个全局函数的名字, 一个匿名函数等等. 函数的原型一定是6bc804a4a90a273c47994d5356043392这个属性必须设置.

skipOnArray: 当输入只是一个数组的时候是否跳过.默认是 false. 请注意,如果过滤器无法处理数组输入,您应该将此属性设置为true。否则,可能会发生一些PHP错误.

小提示: 去空格直接用trim验证.

小提示: 部分封装可以直接使用系统函数如intval:

<&#63;php
['property', 'filter', 'filter' => 'boolval'],
['property', 'filter', 'filter' => 'intval'],
&#63;>

11. image 图片

<&#63;php
[
  // 检查 "primaryImage" 是否是一个有效的图片 且大小合适
  ['primaryImage', 'image', 'extensions' => 'png, jpg',
    'minWidth' => 100, 'maxWidth' => 1000,
    'minHeight' => 100, 'maxHeight' => 1000,
  ],
]
&#63;>

文件验证器的扩展:

minWidth: 最小的宽度 不设无限制.
maxWidth: 最大的宽度 不设无限制.
minHeight: 最小的高度 不设无限制.
maxHeight: 最大的高度 不设无限制.

12. in 在那一个数组里面的值

<&#63;php
[
  // 检查 "level" 是 1, 2 或 3
  ['level', 'in', 'range' => [1, 2, 3]],
]
&#63;>

检查输入的值是否存在于给定的系列值的列表中.

range: 给定范围值的列表.
strict: 输入值和给定值之间的比较结果是否应严格(的类型和值必须相同)。默认为false。
not: 验证结果是否应该被反转。默认为false。当此属性设置为true,验证检查,输入的值不能是给定列表的值中.
allowArray: 是否允许输入值是一个数组。如果这是真的,并输入值是一个数组,数组中的每个元素必须值的给定列表中找到,或验证会失败。

13. integer 整型验证

<&#63;php
[
  // 检查 "age" 是一个整型值
  ['age', 'integer'],
]
&#63;>

max: 上限 不设不检查.
min: 下限 不设不检查..

14. match 正则匹配检查

<&#63;php
[
  // 检查 "username" 以字母开头,并且只包含文字字符
  ['username', 'match', 'pattern' => '/^[a-z]\w*$/i']
]
&#63;>

输入值指定的正则表达式匹配验证检查.

pattern: 输入值必须匹配的规则. 属性必须设置,否则将会抛出异常.
not: 是否反转验证结果. 默认 false.

15. number 数字检查

<&#63;php
[
  // 检查 "salary" 是一个数字
  ['salary', 'number'],
]
&#63;>

相当于double验证器.

max: 上限 不设不检查.
min: 下限 不设不检查.

16. required  是否为空检查

<&#63;php
[
  // 检查 "username" 和 "password" 不是空的
  [['username', 'password'], 'required'],
]
&#63;>

该验证器阻止用户提交空的表单数据.

requiredValue: 应该输入的值. 如果未设 意味着输入值 不应该为空.
strict: 验证一个值时是否应该检查数据类型. 默认false.当 requiredValue未设置时,如果这个属性是 true, 验证器会检查输入值不严格null;如果改属性false,验证器将使用一个松散的规则来确定一个值是空的或不. 当 requiredValue设置了,输入和requiredValue之间的比较也将检查数据类型,如果此属性为true。

17. safe  标记输入是安全属性

<&#63;php
[
  // 标记 "description" 是一个 safe 的属性
  ['description', 'safe'],
]
&#63;>

这个验证器不会执行数据验证.相反, 它是用来标记的属性是一个安全属性(我猜作用是不会进行字符转义吧)。

18. string 字符串验证

<&#63;php
[
  // 检查 "username"是一个 string 而且长度在 4 和 24 之间
  ['username', 'string', 'length' => [4, 24]],
]
&#63;>

这个验证器检查输入的值是一个字符串且长度在确定的值的范围里。

length: 指定待验证的字符串的长度. 可以指定以下形式:
   一个整数: 字符串的精确长度;
   单个数组元素: 输入的最小长度 (e.g. [8]). 必须超过或等于这个数
   两个数组元素: 输入的最小长度和最大长度 (e.g. [8, 128]).
min: 输入字符串的最小长度 未设不限制.
max: 输入字符串的最大长度 未设不限制..
encoding: 输入字符串的编码 未设默认 UTF-8.

19. trim 去空格

<&#63;php
[
  // 去掉 "username" 和 "email" 两边的空格
  [['username', 'email'], 'trim'],
]
&#63;>

不进行数据验证 只进行去空格 如果属性是一个数组 将会自动忽略此过滤.

20. unique 唯一性验证

<&#63;php
[
  // a1 需要是在由“a1”属性表示的列中的唯一
  ['a1', 'unique'],
  // a1 必须是唯一的,但列a2将用于检查的a1值的唯一性
  ['a1', 'unique', 'targetAttribute' => 'a2'],
  // a1和a2的需要是唯一的,并且它们都将收到错误消息
  [['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']],
  // a1和a2的需要是唯一的,只有a1将收到错误消息
  ['a1', 'unique', 'targetAttribute' => ['a1', 'a2']],
  // a1需要通过检查的两个a2和a3的唯一性(使用a1的值)是唯一的
  ['a1', 'unique', 'targetAttribute' => ['a2', 'a1' => 'a3']],
]
&#63;>

这验证检查,如果输入的值是表列中的唯一。它仅适用于活动记录模型的属性。它支持验证对任何单个列或多个列。

targetClass: 应该是被用于验证查找输入值的活动记录类的名字。如果没有设置,将要使用的类目前正在验证该模型的.
targetAttribute: 应该用来验证输入值的唯一性在targetClass的属性的名称。如果没有设置,将使用目前正在验证的属性的名称。可以使用阵列来验证多列的唯一性的同时。数组的值是将被用于验证唯一性的属性,而数组键是其值要验证的属性。如果键和值都是一样的,你可以指定的值。
filter: a额外的过滤器被应用到用于检查输入值的唯一性的数据库查询。这可以是一个字符串或代表附加查询条件的数组(参考 yii\db\Query::where() 查询条件的格式), 或者是一个匿名函数像: function ($query), 其中$query是你可以在函数修改查询对象。
http://www.yiiframework.com/doc-2.0/yii-db-query.html#where()-detail

21. url 地址验证

<&#63;php
[
  // 检查 "website" 是一个有效的 URL. 前置 "http://" 到 "website" 属性
  // 如果它不具有一个URI模式
  ['website', 'url', 'defaultScheme' => 'http'],
]
&#63;>

validSchemes: 一个数组指定URI方案应被认为有效。默认为['HTTP','HTTPS'],意思是HTTP和HTTPS URL被认为是有效的。
defaultScheme: 默认URI方案要预先考虑到输入,如果它不具有方案的一部分。默认为null,意味着不修改输入值。
enableIDN:验证是否应考虑到IDN(国际化域名)。默认为false。需要注意的是,为了使用IDN验证您必须安装并启用国际PHP扩展,否则异常将会被抛出。

更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn