验证组件¶
概览¶
Phalcon\Filter\Validation是一个独立的验证组件,用于验证任意数据集。该组件可用于对不属于模型或集合的数据对象实施验证规则。
下面的例子展示了其基本用法:
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\Email;
use Phalcon\Filter\Validation\Validator\PresenceOf;
$validation = new Validation();
$validation->add(
'name',
new PresenceOf(
[
'message' => 'The name is required',
]
)
);
$validation->add(
'email',
new PresenceOf(
[
'message' => 'The e-mail is required',
]
)
);
$validation->add(
'email',
new Email(
[
'message' => 'The e-mail is not valid',
]
)
);
$messages = $validation->validate($_POST);
if (count($messages)) {
foreach ($messages as $message) {
echo $message, '<br>';
}
}
这个组件的松耦合设计允许你创建自己的验证器,同时还可以使用框架提供的验证器。
方法¶
为字段添加一个验证器 将消息追加到消息列表中 将数据分配给实体。实体用于获取验证值 返回绑定的实体 返回所有过滤器或指定的一个过滤器 获取字段的标签 返回已注册的验证器 返回添加到验证中的验证器 从数组/对象数据源获取要验证的值 从对象实体源获取要验证的值 从数组/对象数据源获取要验证的值 的别名add
方法可以实现反向操作。 为字段添加验证器 设置绑定的实体 为字段添加过滤器 为字段添加标签 根据一组规则验证一组数据 激活¶
验证链可以通过直接向Phalcon\Filter\Validation对象添加验证器来初始化。你可以将你的验证放在单独的文件中以获得更好的代码复用和组织结构。
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\Email;
use Phalcon\Filter\Validation\Validator\PresenceOf;
class MyValidation extends Validation
{
public function initialize()
{
$this->add(
'name',
new PresenceOf(
[
'message' => 'The name is required',
]
)
);
$this->add(
'email',
new PresenceOf(
[
'message' => 'The e-mail is required',
]
)
);
$this->add(
'email',
new Email(
[
'message' => 'The e-mail is not valid',
]
)
);
}
}
然后初始化并使用你自己的验证器:
<?php
$validation = new MyValidation();
$messages = $validation->validate($_POST);
if (count($messages)) {
foreach ($messages as $message) {
echo $message, '<br>';
}
}
验证器¶
Phalcon 为此组件提供了一组内置的验证器:
Alnum¶
检查是否为字母数字字符
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\Alnum;
$validator = new Validation();
$validator->add(
"username",
new Alnum(
[
"message" => ":field must contain only alphanumeric characters",
]
)
);
$validator->add(
[
"username",
"name",
],
new Alnum(
[
"message" => [
"username" => "username must contain only alphanumeric characters",
"name" => "name must contain only alphanumeric characters",
],
]
)
);
Alpha¶
检查是否为字母字符
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\Alpha;
$validator = new Validation();
$validator->add(
"username",
new Alpha(
[
"message" => ":field must contain only letters",
]
)
);
$validator->add(
[
"username",
"name",
],
new Alpha(
[
"message" => [
"username" => "username must contain only letters",
"name" => "name must contain only letters",
],
]
)
);
Between¶
验证值是否处于两个值之间的包含范围内。如果值L
,最小值小于或等于L
和L
小于或等于最大值。边界值也包含在验证范围内。公式为:
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\Between;
$validator = new Validation();
$validator->add(
"price",
new Between(
[
"minimum" => 0,
"maximum" => 100,
"message" => "The price must be between 0 and 100",
]
)
);
$validator->add(
[
"price",
"amount",
],
new Between(
[
"minimum" => [
"price" => 0,
"amount" => 0,
],
"maximum" => [
"price" => 100,
"amount" => 50,
],
"message" => [
"price" => "The price must be between 0 and 100",
"amount" => "The amount must be between 0 and 50",
],
]
)
);
Callback¶
通过使用Phalcon\Filter\Validation\Validator\Callback你可以执行一个自定义函数,该函数必须返回布尔值或一个新的验证器类,该类将用于验证同一个字段。返回true
即视为验证成功,返回false
视为验证失败。执行此验证器时,Phalcon 将根据传入的内容传递数据——如果它是实体(例如模型、stdClass
等),则会传递该实体,否则传递数据(例如像$_POST
这样的数组)。以下是一个示例:
<?php
use \Phalcon\Filter\Validation;
use \Phalcon\Filter\Validation\Validator\Callback;
use \Phalcon\Filter\Validation\Validator\PresenceOf;
$validation = new Validation();
$validation->add(
'amount',
new Callback(
[
'callback' => function ($data) {
return $data['amount'] % 2 == 0;
},
'message' => 'Only even number of products are accepted'
]
)
);
$validation->add(
'amount',
new Callback(
[
'callback' => function ($data) {
if ($data['amount'] % 2 == 0) {
return $data['amount'] != 2;
}
return true;
},
'message' => "You cannot buy 2 products"
]
)
);
$validation->add(
'description',
new Callback(
[
'callback' => function ($data) {
if ($data['amount'] >= 10) {
return new PresenceOf(
[
'message' => 'You must write why you need so big amount.'
]
);
}
return true;
}
]
)
);
// Validator #1
$messages = $validation->validate(['amount' => 1]);
// Validator #2
$messages = $validation->validate(['amount' => 2]);
// Validator #3
$messages = $validation->validate(['amount' => 10]);
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\Callback;
use Phalcon\Filter\Validation\Validator\Numericality;
$validator = new Validation();
$validator->add(
["user", "admin"],
new Callback(
[
"message" => "User cannot belong to two groups",
"callback" => function($data) {
if (!empty($data->getUser()) &&
!empty($data->getAdmin())) {
return false;
}
return true;
}
]
)
);
$validator->add(
"amount",
new Callback(
[
"callback" => function($data) {
if (!empty($data->getProduct())) {
return new Numericality(
[
"message" => "Amount must be a number."
]
);
}
}
]
)
);
Confirmation¶
检查两个值是否相同
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\Confirmation;
$validator = new Validation();
$validator->add(
"password",
new Confirmation(
[
"message" => "Password doesn't match confirmation",
"with" => "confirmPassword",
]
)
);
$validator->add(
[
"password",
"email",
],
new Confirmation(
[
"message" => [
"password" => "Password doesn't match confirmation",
"email" => "Email doesn't match confirmation",
],
"with" => [
"password" => "confirmPassword",
"email" => "confirmEmail",
],
]
)
);
CreditCard¶
检查一个值是否具有有效的信用卡号码
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\CreditCard;
$validator = new Validation();
$validator->add(
"creditCard",
new CreditCard(
[
"message" => "The credit card number is not valid",
]
)
);
$validator->add(
[
"creditCard",
"secondCreditCard",
],
new CreditCard(
[
"message" => [
"creditCard" => "The credit card number is not valid",
"secondCreditCard" => "The second credit card number is not valid",
],
]
)
);
日期¶
检查一个值是否为有效日期
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\Date as DateValidator;
$validator = new Validation();
$validator->add(
"date",
new DateValidator(
[
"format" => "d-m-Y",
"message" => "The date is invalid",
]
)
);
$validator->add(
[
"date",
"anotherDate",
],
new DateValidator(
[
"format" => [
"date" => "d-m-Y",
"anotherDate" => "Y-m-d",
],
"message" => [
"date" => "The date is invalid",
"anotherDate" => "The another date is invalid",
],
]
)
);
Digit¶
检查是否为数字字符
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\Digit;
$validator = new Validation();
$validator->add(
"height",
new Digit(
[
"message" => ":field must be numeric",
]
)
);
$validator->add(
[
"height",
"width",
],
new Digit(
[
"message" => [
"height" => "height must be numeric",
"width" => "width must be numeric",
],
]
)
);
Email¶
检查一个值是否具有正确的电子邮件格式。如果要验证的数据包含 UTF-8 字符,你可以设置allowUTF8
选项以true
允许它们。
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\Email;
$validator = new Validation();
$validator->add(
"email",
new Email(
[
"message" => "The e-mail is not valid",
]
)
);
$validator->add(
[
"email",
"anotherEmail",
],
new Email(
[
"message" => [
"email" => "The e-mail is not valid",
"anotherEmail" => "The another e-mail is not valid",
],
]
)
);
$validator->add(
"täst@example.com",
new Email(
[
"message" => "The e-mail is not valid",
"allowUTF8" => true,
]
)
);
排除在¶
检查一个值是否未包含在一组值中
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\ExclusionIn;
$validator = new Validation();
$validator->add(
"status",
new ExclusionIn(
[
"message" => "The status must not be A or B",
"domain" => [
"A",
"B",
],
]
)
);
$validator->add(
[
"status",
"type",
],
new ExclusionIn(
[
"message" => [
"status" => "The status must not be A or B",
"type" => "The type must not be 1 or "
],
"domain" => [
"status" => [
"A",
"B",
],
"type" => [1, 2],
],
]
)
);
文件¶
检查一个值是否具有正确的文件
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\File;
$validator = new Validation();
$validator->add(
"file",
new File(
[
"maxSize" => "2M",
"messageSize" => ":field exceeds the max size (:size)",
"allowedTypes" => [
"image/jpeg",
"image/png",
],
"messageType" => "Allowed file types are :types",
"maxResolution" => "800x600",
"messageMaxResolution" => "Max resolution of :field is :resolution",
]
)
);
$validator->add(
[
"file",
"anotherFile",
],
new File(
[
"maxSize" => [
"file" => "2M",
"anotherFile" => "4M",
],
"messageSize" => [
"file" => "file exceeds the max size 2M",
"anotherFile" => "anotherFile exceeds the max size 4M",
"allowedTypes" => [
"file" => [
"image/jpeg",
"image/png",
],
"anotherFile" => [
"image/gif",
"image/bmp",
],
],
"messageType" => [
"file" => "Allowed file types are image/jpeg and image/png",
"anotherFile" => "Allowed file types are image/gif and image/bmp",
],
"maxResolution" => [
"file" => "800x600",
"anotherFile" => "1024x768",
],
"messageMaxResolution" => [
"file" => "Max resolution of file is 800x600",
"anotherFile" => "Max resolution of file is 1024x768",
],
]
)
);
文件 MIME 类型¶
检查一个值是否具有正确的文件 MIME 类型
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\File\MimeType;
$validator = new Validation();
$validator->add(
"file",
new MimeType(
[
"types" => [
"image/jpeg",
"image/png",
],
"message" => "Allowed file types are :types"
]
)
);
$validator->add(
[
"file",
"anotherFile",
],
new MimeType(
[
"types" => [
"file" => [
"image/jpeg",
"image/png",
],
"anotherFile" => [
"image/gif",
"image/bmp",
],
],
"message" => [
"file" => "Allowed file types are image/jpeg and image/png",
"anotherFile" => "Allowed file types are image/gif and image/bmp",
]
]
)
);
文件分辨率相等¶
检查文件是否有正确的分辨率
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\File\Resolution\Equal;
$validator = new Validation();
$validator->add(
"file",
new Equal(
[
"resolution" => "800x600",
"message" => "The resolution of the field :field has to be equal :resolution",
]
)
);
$validator->add(
[
"file",
"anotherFile",
],
new Equal(
[
"resolution" => [
"file" => "800x600",
"anotherFile" => "1024x768",
],
"message" => [
"file" => "Equal resolution of file has to be 800x600",
"anotherFile" => "Equal resolution of file has to be 1024x768",
],
]
)
);
文件最大分辨率¶
检查文件是否有正确的分辨率
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\File\Resolution\Max;
$validator = new Validation();
$validator->add(
"file",
new Max(
[
"resolution" => "800x600",
"message" => "Max resolution of :field is :resolution",
"included" => true,
]
)
);
$validator->add(
[
"file",
"anotherFile",
],
new Max(
[
"resolution" => [
"file" => "800x600",
"anotherFile" => "1024x768",
],
"included" => [
"file" => false,
"anotherFile" => true,
],
"message" => [
"file" => "Max resolution of file is 800x600",
"anotherFile" => "Max resolution of file is 1024x768",
],
]
)
);
文件最小分辨率¶
检查文件是否有正确的分辨率
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\File\Resolution\Min;
$validator = new Validation();
$validator->add(
"file",
new Min(
[
"resolution" => "800x600",
"message" => "Min resolution of :field is :resolution",
"included" => true,
]
)
);
$validator->add(
[
"file",
"anotherFile",
],
new Min(
[
"resolution" => [
"file" => "800x600",
"anotherFile" => "1024x768",
],
"included" => [
"file" => false,
"anotherFile" => true,
],
"message" => [
"file" => "Min resolution of file is 800x600",
"anotherFile" => "Min resolution of file is 1024x768",
],
]
)
);
文件大小相等¶
检查一个值是否具有正确的文件
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\File\Size;
$validator = new Validation();
$validator->add(
"file",
new Equal(
[
"size" => "2M",
"included" => true,
"message" => ":field exceeds the size (:size)",
]
)
);
$validator->add(
[
"file",
"anotherFile",
],
new Equal(
[
"size" => [
"file" => "2M",
"anotherFile" => "4M",
],
"included" => [
"file" => false,
"anotherFile" => true,
],
"message" => [
"file" => "file does not have the correct size",
"anotherFile" => "anotherFile wrong size (4MB)",
],
]
)
);
文件最大大小¶
检查一个值是否具有正确的文件
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\File\Size;
$validator = new Validation();
$validator->add(
"file",
new Max(
[
"size" => "2M",
"included" => true,
"message" => ":field exceeds the max size (:size)",
]
)
);
$validator->add(
[
"file",
"anotherFile",
],
new Max(
[
"size" => [
"file" => "2M",
"anotherFile" => "4M",
],
"included" => [
"file" => false,
"anotherFile" => true,
],
"message" => [
"file" => "file exceeds the max size 2M",
"anotherFile" => "anotherFile exceeds the max size 4M",
],
]
)
);
文件最小大小¶
检查一个值是否具有正确的文件
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\File\Size;
$validator = new Validation();
$validator->add(
"file",
new Min(
[
"size" => "2M",
"included" => true,
"message" => ":field exceeds the min size (:size)",
]
)
);
$validator->add(
[
"file",
"anotherFile",
],
new Min(
[
"size" => [
"file" => "2M",
"anotherFile" => "4M",
],
"included" => [
"file" => false,
"anotherFile" => true,
],
"message" => [
"file" => "file exceeds the min size 2M",
"anotherFile" => "anotherFile exceeds the min size 4M",
],
]
)
);
完全相同¶
检查一个值是否与其他值相同
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\Identical;
$validator = new Validation();
$validator->add(
"terms",
new Identical(
[
"accepted" => "yes",
"message" => "Terms and conditions must be accepted",
]
)
);
$validator->add(
[
"terms",
"otherTerms",
],
new Identical(
[
"accepted" => [
"terms" => "yes",
"otherTerms" => "yes",
],
"message" => [
"terms" => "Terms and conditions must be accepted",
"otherTerms" => "Other terms must be accepted",
],
]
)
);
包含于¶
检查一个值是否包含在一组值中
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\InclusionIn;
$validator = new Validation();
$validator->add(
"status",
new InclusionIn(
[
"message" => "The status must be A or B",
"domain" => ["A", "B"],
]
)
);
$validator->add(
[
"status",
"type",
],
new InclusionIn(
[
"message" => [
"status" => "The status must be A or B",
"type" => "The status must be 1 or 2",
],
"domain" => [
"status" => ["A", "B"],
"type" => [1, 2],
]
]
)
);
IP 地址¶
检查 IP 地址
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\Ip;
$validator = new Validation();
$validator->add(
"ip_address",
new Ip(
[
"message" => ":field must contain only ip addresses",
// v6 and v4. The same if not specified
"version" => IP::VERSION_4 | Ip::VERSION_6,
// False if not specified. Ignored for v6
"allowReserved" => false,
// False if not specified
"allowPrivate" => false,
"allowEmpty" => false,
]
)
);
$validator->add(
[
"source_address",
"destination_address",
],
new Ip(
[
"message" => [
"source_address" => "source_address must be a valid IP address",
"destination_address" => "destination_address must be a valid IP address",
],
"version" => [
"source_address" => Ip::VERSION_4 | Ip::VERSION_6,
"destination_address" => Ip::VERSION_4,
],
"allowReserved" => [
"source_address" => false,
"destination_address" => true,
],
"allowPrivate" => [
"source_address" => false,
"destination_address" => true,
],
"allowEmpty" => [
"source_address" => false,
"destination_address" => true,
],
]
)
);
数值性¶
检查有效的数值
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\Numericality;
$validator = new Validation();
$validator->add(
"price",
new Numericality(
[
"message" => ":field is not numeric",
]
)
);
$validator->add(
[
"price",
"amount",
],
new Numericality(
[
"message" => [
"price" => "price is not numeric",
"amount" => "amount is not numeric",
]
]
)
);
存在验证¶
验证字段是否存在
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\PresenceOf;
$validation = new Validation();
$validation->add(
'name',
new PresenceOf(
[
'message' => 'The name is required',
]
)
);
);
正则表达式¶
根据正则表达式模式验证字段
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\Regex;
$validation = new Validation();
$validation->add(
'telephone',
new Regex(
[
'message' => 'The telephone is required',
'pattern' => '/\+1 [0-9]+/',
]
)
);
字符串长度¶
验证字符串是否满足指定的最大和最小长度限制。当字符串长度满足条件时验证通过L
,最小值小于或等于L
和L
小于或等于最大值。边界值也包含在验证范围内。公式为:
此验证器的作用类似于容器。
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\StringLength;
$validator = new Validation();
$validation->add(
"name_last",
new StringLength(
[
"max" => 50,
"min" => 2,
"messageMaximum" => "Name too long",
"messageMinimum" => "Only initials please",
"includedMaximum" => true,
"includedMinimum" => false,
]
)
);
$validation->add(
[
"name_last",
"name_first",
],
new StringLength(
[
"max" => [
"name_last" => 50,
"name_first" => 40,
],
"min" => [
"name_last" => 2,
"name_first" => 4,
],
"messageMaximum" => [
"name_last" => "Last name too short",
"name_first" => "First name too short",
],
"messageMinimum" => [
"name_last" => "Last name too long",
"name_first" => "First name too long",
],
"includedMaximum" => [
"name_last" => false,
"name_first" => true,
],
"includedMinimum" => [
"name_last" => false,
"name_first" => true,
]
]
)
);
最大字符串长度¶
验证字符串是否满足指定的最大长度限制。当字符串长度小于或等于最大值时验证通过L
小于或等于最大值。公式为:
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\StringLength\Max;
$validator = new Validation();
$validation->add(
"name_last",
new Max(
[
"max" => 50,
"message" => "Last name too long",
"included" => true
]
)
);
$validation->add(
[
"name_last",
"name_first",
],
new Max(
[
"max" => [
"name_last" => 50,
"name_first" => 40,
],
"message" => [
"name_last" => "Last name too long",
"name_first" => "First name too long",
],
"included" => [
"name_last" => false,
"name_first" => true,
]
]
)
);
最小字符串长度¶
验证字符串是否满足指定的最小长度限制。当字符串长度大于或等于最小值时验证通过L
大于或等于最小值。公式为:
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\StringLength\Min;
$validator = new Validation();
$validation->add(
"name_last",
new Min(
[
"min" => 2,
"message" => "Only initials please",
"included" => true
]
)
);
$validation->add(
[
"name_last",
"name_first",
],
new Min(
[
"min" => [
"name_last" => 2,
"name_first" => 4,
],
"message" => [
"name_last" => "Last name too short",
"name_first" => "First name too short",
],
"included" => [
"name_last" => false,
"name_first" => true,
]
]
)
);
唯一性¶
检查字段在相关表中是否唯一
<?php
use MyApp\Models\Customers;
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\Uniqueness;
$validator = new Validation();
$validator->add(
"cst_email",
new Uniqueness(
[
"model" => new Customers(),
"message" => ":field must be unique",
]
)
);
字段的不同属性:
<?php
$validator->add(
"cst_email",
new Uniqueness(
[
"model" => new Invoices(),
"attribute" => "nick",
]
)
);
在模型中:
模型中的字段组合:
可以在验证之前转换值。这在需要将值转换以便数据库查询时非常有用:
<?php
$validator->add(
"cst_email",
new Uniqueness(
[
"convert" => function (array $values) {
$values["cst_email"] = trim($values["cst_email"]);
return $values;
}
]
)
);
使用排除字段(SQL 操作 "value NOT IN (except)
")¶
单个字段
带键的多个字段(每个排除项将应用于由键定义的值)<?php
$validator->add(
["cst_email", "cst_phone"],
new Uniqueness(
[
"except" => [
"cst_email" => "name@email.com",
"cst_phone" => "82918304-3843",
]
]
)
);
<?php
$validator->add(
["cst_email", "cmp_email"],
new Uniqueness(
[
"except" => [
"name@email.com",
"company@email.com",
],
]
)
);
<?php
$validator->add(
["cst_email", "cmp_email"],
new Uniqueness(
[
"except" => "name@email.com",
]
)
);
URL¶
检查一个值是否具有 URL 格式
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\Url;
$validator = new Validation();
$validator->add(
"url",
new Url(
[
"message" => ":field must be a URL",
]
)
);
$validator->add(
[
"url",
"homepage",
],
new Url(
[
"message" => [
"url" => "url must be a url",
"homepage" => "homepage must be a url",
]
]
)
);
还可以传递flags
数组中的选项,如需定义的话。FILTER_FLAG_PATH_REQUIRED
或FILTER_FLAG_QUERY_REQUIRED
如有需要。
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\Url;
$validation = new Validation();
$validation->add(
'url',
new Url(
[
'options' => FILTER_FLAG_PATH_REQUIRED
]
)
);
$messages = $validation->validate(
[
'url' => 'phalcon.io',
]
);
$validation->add(
'url',
new Url(
[
'options' => FILTER_FLAG_QUERY_REQUIRED
]
)
);
$messages = $validation->validate(
[
'url' => 'https://',
]
);
$validation->add(
'url',
new Url(
[
'options' => [
'flags' => [
FILTER_FLAG_PATH_REQUIRED,
FILTER_FLAG_QUERY_REQUIRED,
],
],
]
)
);
$messages = $validation->validate(
[
'url' => 'phalcon',
]
);
自定义验证器¶
你可以通过实现Phalcon\Filter\Validation\ValidatorInterface或Phalcon\Filter\Validation\Validator\CompositeInterface来创建自己的验证器。你也可以继承Phalcon\Filter\Validation\AbstractCombinedFieldsValidator, Phalcon\Filter\Validation\AbstractValidator或Phalcon\Filter\Validation\AbstractValidatorComposite.
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\AbstractValidator;
class IpValidator extends AbstractValidator
{
/**
* Adding the default template error message
*
* @param array $options
*/
public function __construct(array $options = [])
{
$this->template = 'The IP :ip_address is not valid';
parent::__construct($options);
}
/**
* Executes the validation
*
* @param Validation $validation
* @param string $field
*
* @return boolean
*/
public function validate(Validation $validation, $field)
{
$value = $validation->getValue($field);
if (!filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6)) {
$replacements = [':ip_address' => $value];
$validation->appendMessage(
$this->messageFactory($validation, $field, $replacements)
);
return false;
}
return true;
}
}
重要的是验证器应返回一个有效boolean
值以表明验证是否成功。
消息¶
Phalcon\Filter\Validation使用Phalcon\Messages\Messages集合,提供一种灵活的方式来输出或存储验证过程中生成的验证消息。
每条消息都由Phalcon\Messages\Message类的一个实例组成。可以通过getMessages()
方法获取生成的消息集合。每条消息提供扩展信息,例如生成消息的字段或消息类型:
<?php
$messages = $validation->validate();
if (count($messages)) {
foreach ($messages as $message) {
echo 'Message: ', $message->getMessage(), "\n";
echo 'Field: ', $message->getField(), "\n";
echo 'Type: ', $message->getType(), "\n";
}
}
你可以传递一个message
参数来更改/翻译每个验证器中的默认消息。你还可以在消息中使用占位符:field
,它将被字段标签替换:
<?php
use Phalcon\Filter\Validation\Validator\Email;
$validation->add(
'email',
new Email(
[
'message' => 'The e-mail is not valid',
]
)
);
默认情况下,getMessages()
方法会返回验证期间生成的所有消息。你可以使用filter()
方法:
<?php
$messages = $validation->validate();
if (count($messages)) {
$filteredMessages = $messages->filter('name');
foreach ($filteredMessages as $message) {
echo $message;
}
}
来过滤特定字段的消息:¶
数据过滤
<?php
use Phalcon\Filter\Validation;
$validation = new Validation();
$validation->add(
'name',
new PresenceOf(
[
'message' => 'The name is required',
]
)
);
$validation->add(
'email',
new PresenceOf(
[
'message' => 'The email is required',
]
)
);
$validation->setFilters('name', 'trim');
$validation->setFilters('email', 'trim');
验证前可对数据进行过滤,确保不会对恶意或错误的数据进行验证。过滤器组件执行过滤与清理操作。你可以向此组件添加更多的过滤器或使用内置的过滤器。
事件¶
当验证组织成类时,你可以实现beforeValidation()
和afterValidation()
方法以执行其他检查、过滤、清理等操作。如果beforeValidation()
方法返回 false,则自动取消验证:
<?php
use Phalcon\Http\Request;
use Phalcon\Messages\Message;
use Phalcon\Filter\Validation;
/**
* @property Request $request
*/
class LoginValidation extends Validation
{
public function initialize()
{
// ...
}
public function beforeValidation($data, $entity, $messages)
{
if ($this->request->getHttpHost() !== 'admin.mydomain.com') {
$messages->appendMessage(
new Message(
'Only users can log on in the admin domain'
)
);
return false;
}
return true;
}
public function afterValidation($data, $entity, $messages)
{
// ... Add additional messages or perform more validations
}
}
取消验证¶
默认情况下,分配给字段的所有验证器都会被测试,无论其中一个验证器是否失败。你可以通过告诉验证组件哪个验证器可能停止验证来更改此行为:
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\Regex;
use Phalcon\Filter\Validation\Validator\PresenceOf;
$validation = new Validation();
$validation->add(
'telephone',
new PresenceOf(
[
'message' => 'The telephone is required',
'cancelOnFail' => true,
]
)
);
$validation->add(
'telephone',
new Regex(
[
'message' => 'The telephone is required',
'pattern' => '/\+44 [0-9]+/',
]
)
);
$validation->add(
'telephone',
new StringLength(
[
'messageMinimum' => 'The telephone is too short',
'min' => 2,
]
)
);
第一个验证器具有cancelOnFail
选项且值为true
,因此如果该验证器失败,则链中的其余验证器不会被执行。
如果你正在创建自定义验证器,可以通过设置cancelOnFail
选项动态停止验证链:
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator;
use Phalcon\Messages\Message;
class MyValidator extends Validator
{
public function validate(Validation $validator, $attribute)
{
// If the attribute value is `name` we must stop the chain
if ($attribute === 'name') {
$validator->setOption('cancelOnFail', true);
}
// ...
}
}
空值处理¶
您可以传递选项allowEmpty
对内置验证器而言,用于忽略空值。
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\Regex;
$validation = new Validation();
$validation->add(
'telephone',
new Regex(
[
'message' => 'The telephone is required',
'pattern' => '/\+1 [0-9]+/',
'allowEmpty' => true,
]
)
);
The allowEmpty
选项也可以是一个字段名数组。匹配该数组中元素的字段会在其值为空时进行验证。true
如果它们具有空值,则会触发验证失败。
递归验证¶
你还可以通过afterValidation()
方法在一个验证实例内部运行另一个验证实例。在此示例中,验证CompanyValidation
实例还将检查PhoneValidation
实例:
<?php
use Phalcon\Filter\Validation;
class CompanyValidation extends Validation
{
/**
* @var PhoneValidation
*/
protected $phoneValidation;
public function initialize()
{
$this->phoneValidation = new PhoneValidation();
}
public function afterValidation($data, $entity, $messages)
{
$phoneValidationMessages = $this->phoneValidation->validate(
$data['phone']
);
$messages->appendMessages(
$phoneValidationMessages
);
}
}
异常¶
在Phalcon\Filter\Validation
命名空间将是类型Phalcon\Filter\Validation\Exception或Phalcon\Filter\Validation\Validator\Exception。你可以使用此异常选择性地捕获仅从此组件抛出的异常。
<?php
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Exception;
use Phalcon\Filter\Validation\Validator\InclusionIn;
try {
$validator = new Validation();
$validator->add(
"status",
new InclusionIn(
[
"message" => "The status must be A or B",
"domain" => false,
]
)
);
} catch (Exception $ex) {
echo $ex->getMessage();
}