入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

Yii2 理解Validator

创建时间:2017-01-11 投稿人: 浏览次数:1708

    • 版本
    • Validator
    • BooleanValidator
    • CompareValidator
    • DateValidator
    • DefaultValueValidator
    • EachValidator
    • EmailValidator
    • ExistValidator
    • FileValidator
    • FilterValidator
    • ImageValidator
    • IpValidator
    • NumberValidator
    • RangeValidator
    • RegularExpressionValidator
    • RequiredValidator
    • SafeValidator
    • StringValidator
    • UniqueValidator
    • UrlValidator
    • CaptchaValidator
    • 验证流程

1 版本

// yiiBaseYiigetVersion
public static function getVersion()
{
    return "2.0.10";
}

2 Validator

其它验证器的基类

$attributes, 等待验证的输入值,可以是字符串,也可以是数组
$message, 自定义的错误信息
$on, 使用的场景,根据scenarios来判断,可以是字符串,也可以是数组。
$except, 不开启规则验证的场景。可以是字符串,也可以是数组。

3 BooleanValidator

检查属性的值是否为布尔值
‘boolean’ => ‘yiivalidatorsBooleanValidator’

$trueValue, 表示真的状态, 默认用1来表示。
$falseValue, 表示假的状态, 默认用0来表示。
$strict, 是否严格匹配, 默认为false,如果为true, 则被验证的对象真假必须和$trueValue, $falseValue相同。
// rememberMe的值必须是true或者false,否则检查失败
["rememberMe", "boolean", "trueValue" => true, "falseValue" => false, "strict" => true],

4 CompareValidator

比较两个值的结果是否满足条件
‘compare’ => ‘yiivalidatorsCompareValidator’

$compareAttribute, 要验证的属性$a, 要被比对的属性$b = $a._repeat
$compareValue, 用于与输入值进行比较的常量值
$type, 要验证对象的类型, 默认为string, 另一个类型为number
$operator, 操作符, 默认为==
$message, 自定义错误消息, 可以使用占位符
- `{attribute}`: the label of the attribute being validated
- `{value}`: the value of the attribute being validated
- `{compareValue}`: the value or the attribute label to be compared with
- `{compareAttribute}`: the label of the attribute to be compared with
- `{compareValueOrAttribute}`: the value or the attribute label to be compared with
// 验证password和password_repeat是否相同
["password", "compare"],
// age必须要>= 18
["age", "compare", "compareValue" => 18, "operator" => ">="]

5 DateValidator

检验属性值是否为正确的日期格式
‘date’ => ‘yiivalidatorsDateValidator’
‘datetime’ => [
‘class’ => ‘yiivalidatorsDateValidator’,
‘type’ => DateValidator::TYPE_DATETIME,
]
‘time’ => [
‘class’ => ‘yiivalidatorsDateValidator’,
‘type’ => DateValidator::TYPE_TIME,
]

$type, 日期类型,默认为date,另外有datetime, time
["create_t", "date"],

6 DefaultValueValidator

给属性设置默认值的
‘default’ => ‘yiivalidatorsDefaultValueValidator’

$value, 默认的值,或者是有返回值的匿名函数
$skipOnEmpty, 默认为false, 如果为true, 则当只不存在的时候,就会被跳过,而不会赋值$value
// 来访用户默认为 vistor
["group", "default", "value" => "visitor"]

7 EachValidator

判断数组中的每个元素是否符合规则
‘each’ => ‘yiivalidatorsEachValidator’

["categoryIDs", "each", "rule" => ["integer"]],

8 EmailValidator

检测属性值是否是正确的电子邮件格式
‘email’ => ‘yiivalidatorsEmailValidator’

$pattern, $fullPattern一般都使用默认
["email", "email"]

9 ExistValidator

用来检测在数据表中是否已经存在此属性值
‘exist’ => ‘yiivalidatorsExistValidator’

$targetClass, 用于验证的ActiveRecord派生类,如果没有指定,则默认为当前执行验证的ActiveRecord派生类
$targetAttribute, 用于检测的ActiveRecord派生类中的属性名, 如果没有指定,则使用输入值的名称。
这个也可以是数组,键和值相同,比如["account"=>"account", "email"=>"email"],
也可以写成 ["account", "email"]
$filter,用于增加更多的数据库查询条件
[["account", "email"], "exist"]

10 FileValidator

用于验证上传文件的属性, 需要开启php扩展:fileinfo
‘file’ => ‘yiivalidatorsFileValidator’

$extensions, 允许上传的文件扩展名,可以是字符串,也可以是数组, ["png", "jpg", "gif"]
$checkExtensionByMimeType, 是否通过文件的MIME类型来判断文件扩展, 如果MIME判断的文件扩展和给定的文件扩展不同,则判定无效,默认为true.
$mimeTypes, 可接受上传的MIME类型名 ["image/png", "application/zip"]
$minSize, 文件容量最小值, byte, 默认为null,表示没有限制。
$maxSize,文件容量最大值, byte, 默认为null,表示没有限制。
$maxFiles,允许上传的文件数量,默认为1,如果设置为0, 则表示没有任何限制。此字段还受到php.ini max_file_uploads字段影响, 默认为20。
$message, 报错,文件没有正确的上传
$uploadRequired,报错,没有文件上传
$tooBig,文件大小超出maxSize, 占位符:
- {attribute}: the attribute name
- {file}: the uploaded file name
- {limit}: the maximum size allowed (see [[getSizeLimit()]])
- {formattedLimit}: the maximum size formatted with [[yiii18nFormatter::asShortSize()|Formatter::asShortSize()]]
$tooSmall,文件大小低于minSize, 占位符:
- {attribute}: the attribute name
- {file}: the uploaded file name
- {limit}: the maximum size allowed (see [[getSizeLimit()]])
- {formattedLimit}: the maximum size formatted with [[yiii18nFormatter::asShortSize()|Formatter::asShortSize()]]
$tooMany,文件数量超出了限制,占位符:
- {attribute}: the attribute name
- {limit}: the value of [[maxFiles]]
$wrongExtension,文件扩展名不符合条件, 占位符:
- {attribute}: the attribute name
- {file}: the uploaded file name
- {extensions}: the list of the allowed extensions.
$wrongMimeType,文件MIME类型不符合条件,占位符:
- {attribute}: the attribute name
- {file}: the uploaded file name
- {mimeTypes}: the value of [[mimeTypes]]
["uploadFile", "file", "extensions" => ["png", "jpg", "gif"], "maxSize" => 2 * 1024 * 1024]

11 FilterValidator

对属性值进行加工处理后返回
‘filter’ => ‘yiivalidatorsFilterValidator’

$filter, 处理函数,可以是全局函数,匿名函数, 不可为空。函数应该像这样
function func($value)
{
    // todo $value->$newValue;
    // return $newValue;
}
$skipOnArray, 如果输入值为array,是否略过,默认为false。如果此处为true,且输入值为array,就会报错。
["title", "filter", "filter" => function($value) { return Html::encode($value); }]
["age", "filter", "filter" => "intval"]

12 ImageValidator

用于验证是否有效的图片文件,派生于FileValidator
‘image’ => ‘yiivalidatorsImageValidator’

$minWidth, 最小宽度,像素
$maxWidth, 最大宽度,像素
$minHeight, 最小高度,像素
$maxHeight, 最大高度,像素 
$notImage, 报错, 上传的文件并非图片文件
$underWidth, 报错, 低于最小宽度
$overWidth, 报错, 超出最大宽度
$underHeight, 报错, 低于最小高度
$overHeight, 报错, 超出最大宽度
["uploadImage", "image", "extensions" => ["png"], "minWidth" => 200, "maxWidth" => 400,
"minHeight" => 400, "maxHeight" => 400]

13 IpValidator

验证有效的IPv4/IPv6网址
‘ip’ => ‘yiivalidatorsIpValidator’

ipv6, 是否可以是IPv6, 默认为true
ipv4, 是否可以是IPv4, 默认为true
$subnet, 是否可以使CIDR网络。
- `false` - the address must not have a subnet (default).
- `true` - specifying a subnet is required.
- `null` - specifying a subnet is optional.
$message, 报错,因为错误的地址格式验证失败。
["ipAddress", "ip", "ipv6" => false]

14 NumberValidator

验证是否为数字,过滤器可以是number, double, integer
‘number’ => ‘yiivalidatorsNumberValidator’,
‘integer’ => [
‘class’ => ‘yiivalidatorsNumberValidator’,
‘integerOnly’ => true,
]
‘double’ => ‘yiivalidatorsNumberValidator’

$max, 数字上限, 默认为null, 表示不检查上限
$min, 数字下限, 默认为null, 表示不检查下限
$integerOnly, 表示是否只是整型,默认为false
true: preg_match $integerPattern
false: preg_match $numberPattern
$tooBig, 报错,表示高于下限值
$tooSmall, 报错,表示低于下限值
["age", "integer", "min" => 18]
["money", "number"]

15 RangeValidator

验证输入值是否在给定的范围之内
‘in’ => ‘yiivalidatorsRangeValidator’

$range, 范围,可以是array,或者返回array的匿名函数
$strict, 是否要严格相同,类型和值, ===, 默认为false
$not, 是否将结果取反,变成判定输入值是否在给定值范围之外, 默认为false
$allowArray, 输入是否可以为array,默认为false, 如果为true, 则array中所有值都需要验证通过
["group", "in", "range" => ["admin", "vip"]]

16 RegularExpressionValidator

用来检测属性值是否匹配给出的正则表达式
‘match’ => ‘yiivalidatorsRegularExpressionValidator’

$pattern, 用于检测的正则表达式
$not, 是否将结果取反, 默认为false
["username", "match", "pattern" => "/^[a-z]w*$/i", "message" => "用户名不符合"]

17 RequiredValidator

验证输入值是否为空, 或者是否与给定值相同
‘required’ => ‘yiivalidatorsRequiredValidator’

$skipOnEmpty, 
$requiredValue, 默认为null
如果为null,则输入值只要判定是否为空。
如果设置了值,则输入值还要判定是否与其相同。
$strict, 默认为false
如果为true, 则输入值和$requiredValue必须类型和值都要相同,即使$requiredValue为null。
如果为false, 且$requiredValue设置了值,则输入值和$requiredValue只要值相同即可。
如果为false, 且$requiredValue为null,则使用isEmpty判断输入值是否为空。
$message, 玩家定义错误信息,包含以下占位符:
- `{attribute}`: the label of the attribute being validated
- `{value}`: the value of the attribute being validated
- `{requiredValue}`: the value of [[requiredValue]]

18 SafeValidator

将属性认为是安全的,并不进行任何验证。
比如常常用post提交一些值给model,yii假设所有的值都是不安全的,而该验证器标记指定的属性是安全的。
‘safe’ => ‘yiivalidatorsSafeValidator’

TODO: SafeValidator工作方式

19 StringValidator

对属性值进行长度进行判断
‘string’ => ‘yiivalidatorsStringValidator’

$length 长度限制
如果为整型,则为期望输入的长度值。不一样则会报错$notEqual
如果为数组,且只有一个元素,则为最小值$min, [6]
如果为数组,且只有两个元素,则分别为最小值$min,最大值$max, [6, 20]
$min, 最小值,不设置则不检测最小值,低于最小值会报错$tooShort
$max, 最大值,不设置则不检测最大值,超出最大值会报错$tooLong
$encoding, 字符串编码方式,默认为utf-8
// 密码长度需要在6~20位之间
["password", "string", "length" => [6, 20]]

20 UniqueValidator

验证输入值在指定的表中是否唯一
‘unique’ => ‘yiivalidatorsUniqueValidator’

$targetClass, 用于验证的ActiveRecord派生类,如果没有指定,则默认为当前执行验证的ActiveRecord派生类
$targetAttribute, 用于检测的ActiveRecord派生类中的属性名, 如果没有指定,则使用输入值的名称。
这个也可以是数组,键和值相同,比如["account"=>"account", "email"=>"email"],
也可以写成 ["account", "email"]
$filter, 用于增加更多的数据库查询条件
$message, 自定义的错误信息, 占位符:
- `{attribute}`: the label of the attribute being validated
- `{value}`: the value of the attribute being validated
当输入为数组的时候:
- `{attributes}`: the labels of the attributes being validated.
- `{values}`: the values of the attributes being validated.
["email", "unique"]
["email", "unique", "targetClass" => "commonmodelsUser", "targetAttribute" => "mail"]

22 UrlValidator

用于检测输入值是否是一个有效的url地址
‘url’ => ‘yiivalidatorsUrlValidator’

$pattern, 用于验证的正则表达式,内含$schemes做为前缀
$validSchemes, 用于指定哪些url会被当成有效的url地址,默认为[http, https]
$defaultScheme, 如果输入值中没有$schemes做为前缀,则会使用该值,默认为null,表示不改变输入值
enableIDN, 是否使用IDN,国际化域名,比如中文域名,需要intl PHP扩展,默认为false。
["website", "url"]

23 CaptchaValidator

对验证码进行验证
‘captcha’ => ‘yiicaptchaCaptchaValidator’

TODO

24 验证流程

示例

// commonmodelsRegisterForm.php
class RegisterForm extends Model
{
    public $username;
    public $password;

    public function rules()
    {
        return [
            [["username", "password"], "required"],
            ["username", "unique", "targetClass" => "commonmodelsUser", "message" => "用户名已存在"]
            ["username", "string", "min" => 2, "max" => 40],
            ["password", "string", "length" => [6, 20]],
            // 自定义验证器
            ["username", "checkValid"]
        ];
    }

    public function register()
    {
        if ($this->validate())
        {
            return null;
        }
        ...
    }

    // 自定义的验证器, 必须符合 public function func($attribute, $params) {} 格式
    public function checkValid($attribute, $params)
    {
        // 验证不可以全为数字
        // 验证不可以为数字开头
    }
}

当用户提交的时候,会走到RegisterForm::register(), 在其中需要手动调用$this->validate()来是rules生效。

// yiiaseModel
public function validate($attributeNames = null, $clearErrors = true)
{
    ...
    foreach ($this->getActiveValidators() as $validator) 
    {
        // Validator的派生类中需要重载validateValue或者validateAttribute函数
        $validator->validateAttributes($this, $attributeNames);
    }
    ...
    return !$this->hasErrors();
}

TOP

声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。