# Validating Models
## 验证数据完整性(Validating Data Integrity)
[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html)provides several events to validate data and implement business rules. The special “validation” event allows us to call built-in validators over the record. Phalcon exposes a few built-in validators that can be used at this stage of validation.
The following example shows how to use it:
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
use Phalcon\Validation;
use Phalcon\Validation\Validator\Uniqueness;
use Phalcon\Validation\Validator\InclusionIn;
class Robots extends Model
{
public function validation()
{
$validator = new Validation();
$validator->add(
"type",
new InclusionIn(
[
"domain" => [
"Mechanical",
"Virtual",
]
]
)
);
$validator->add(
"name",
new Uniqueness(
[
"message" => "The robot name must be unique",
]
)
);
return $this->validate($validator);
}
}
~~~
The above example performs a validation using the built-in validator “InclusionIn”. It checks the value of the field “type” in a domain list. If the value is not included in the method then the validator will fail and return false.
> For more information on validators, see the[Validation documentation](http://docs.iphalcon.cn/reference/validation.html).
The idea of creating validators is make them reusable between several models. A validator can also be as simple as:
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Message;
class Robots extends Model
{
public function validation()
{
if ($this->type === "Old") {
$message = new Message(
"Sorry, old robots are not allowed anymore",
"type",
"MyType"
);
$this->appendMessage($message);
return false;
}
return true;
}
}
~~~
## 验证信息(Validation Messages)
[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html)has a messaging subsystem that provides a flexible way to output or store the validation messages generated during the insert/update processes.
Each message is an instance of[Phalcon\\Mvc\\Model\\Message](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model_Message.html)and the set of messages generated can be retrieved with the`getMessages()`method. Each message provides extended information like the field name that generated the message or the message type:
~~~
<?php
if ($robot->save() === false) {
$messages = $robot->getMessages();
foreach ($messages as $message) {
echo "Message: ", $message->getMessage();
echo "Field: ", $message->getField();
echo "Type: ", $message->getType();
}
}
~~~
[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html)can generate the following types of validation messages:
| Type | Description |
| --- | --- |
| PresenceOf | Generated when a field with a non-null attribute on the database is trying to insert/update a null value |
| ConstraintViolation | Generated when a field part of a virtual foreign key is trying to insert/update a value that doesn’t exist in the referenced model |
| InvalidValue | Generated when a validator failed because of an invalid value |
| InvalidCreateAttempt | Produced when a record is attempted to be created but it already exists |
| InvalidUpdateAttempt | Produced when a record is attempted to be updated but it doesn’t exist |
The`getMessages()`method can be overridden in a model to replace/translate the default messages generated automatically by the ORM:
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public function getMessages()
{
$messages = [];
foreach (parent::getMessages() as $message) {
switch ($message->getType()) {
case "InvalidCreateAttempt":
$messages[] = "The record cannot be created because it already exists";
break;
case "InvalidUpdateAttempt":
$messages[] = "The record cannot be updated because it doesn't exist";
break;
case "PresenceOf":
$messages[] = "The field " . $message->getField() . " is mandatory";
break;
}
}
return $messages;
}
}
~~~
## 验证失败事件(Validation Failed Events)
Another type of events are available when the data validation process finds any inconsistency:
| Operation | Name | Explanation |
| --- | --- | --- |
| Insert or Update | notSaved | Triggered when the INSERT or UPDATE operation fails for any reason |
| Insert, Delete or Update | onValidationFails | Triggered when any data manipulation operation fails |
- 简介
- 安装
- 安装(installlation)
- XAMPP下的安装
- WAMP下安装
- Nginx安装说明
- Apache安装说明
- Cherokee 安装说明
- 使用 PHP 内置 web 服务器
- Phalcon 开发工具
- Linux 系统下使用 Phalcon 开发工具
- Mac OS X 系统下使用 Phalcon 开发工具
- Windows 系统下使用 Phalcon 开发工具
- 教程
- 教程 1:让我们通过例子来学习
- 教程 2:INVO简介
- 教程 3: 保护INVO
- 教程4: 使用CRUD
- 教程5: 定制INVO
- 教程 6: Vökuró
- 教程 7:创建简单的 REST API
- 组件
- 依赖注入与服务定位器
- MVC架构
- 使用控制器
- 使用模型
- 模型关系
- 事件与事件管理器
- Behaviors
- 模型元数据
- 事务管理
- 验证数据完整性
- Workingwith Models
- Phalcon查询语言
- 缓存对象关系映射
- 对象文档映射 ODM
- 使用视图
- 视图助手
- 资源文件管理
- Volt 模版引擎
- MVC 应用
- 路由
- 调度控制器
- Micro Applications
- 使用命名空间
- 事件管理器
- Request Environmen
- 返回响应
- Cookie 管理
- 生成 URL 和 路径
- 闪存消息
- 使用 Session 存储数据
- 过滤与清理
- 上下文编码
- 验证Validation
- 表单_Forms
- 读取配置
- 分页 Pagination
- 使用缓存提高性能
- 安全
- 加密与解密 Encryption/Decryption
- 访问控制列表
- 多语言支持
- 类加载器 Class Autoloader
- 日志记录_Logging
- 注释解析器 Annotations Parser
- 命令行应用 Command Line Applications
- Images
- 队列 Queueing
- 数据库抽象层
- 国际化
- 数据库迁移
- 调试应用程序
- 单元测试
- 进阶技巧与延伸阅读
- 提高性能:下一步该做什么?
- Dependency Injection Explained
- Understanding How Phalcon Applications Work
- Api
- Abstract class Phalcon\Acl