Yii核心验证器api详解

2019-05-02 12:13:23丽君

8. exist 是否存在

<?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],
]
?>

这个验证器检查输入的值能否被找到在在对应的表的列值里,他只会在 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 yiidbQuery::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 文件验证

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

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

extensions: 允许上传的文件类型列表.他可以是一个数组 或者是一个以逗号分割的字符串(如. "gif, jpg"). 扩展名不区分大小写,默认为 null, 意味着所有的文件扩展名是允许的.
mimeTypes: 允许上传的文件资源的媒体类型。他可以是一个数组 或者是一个以逗号或空格分割的字符串 (如. "image/jpeg, image/png"). 不区分大小写,默认为 null, 意味着所有的文件扩展名是允许的.
minSize: 上传文件的最小字节数 未设不做判断.

相关文章 大家在看