我以前用过Yii框架。我想用Phalcon做项目。我找不到Phalcon的验证方案。在Phalcon上正确实现它的最佳方法是什么?
提前谢谢。
发布于 2014-03-19 10:21:21
任何数据验证:
<?php
use Phalcon\Validation\Validator\PresenceOf,
Phalcon\Validation\Validator\Email;
$validation = new Phalcon\Validation();
$validation->add('name', new PresenceOf(array(
'message' => 'The name is required'
)));
$validation->add('email', new PresenceOf(array(
'message' => 'The e-mail is required'
)));
$validation->add('email', new Email(array(
'message' => 'The e-mail is not valid'
)));
$messages = $validation->validate($_POST);
if (count($messages)) {
foreach ($messages as $message) {
echo $message, '<br>';
}
}http://docs.phalconphp.com/en/1.2.6/reference/validation.html
如果您正在使用模型:
<?php
use Phalcon\Mvc\Model\Validator\InclusionIn,
Phalcon\Mvc\Model\Validator\Uniqueness;
class Robots extends \Phalcon\Mvc\Model
{
public function validation()
{
$this->validate(new InclusionIn(
array(
"field" => "type",
"domain" => array("Mechanical", "Virtual")
)
));
$this->validate(new Uniqueness(
array(
"field" => "name",
"message" => "The robot name must be unique"
)
));
return $this->validationHasFailed() != true;
}
}http://docs.phalconphp.com/en/1.2.6/reference/models.html#validating-data-integrity
模型也有事件,因此可以在这些函数中添加所需的任何逻辑:
http://docs.phalconphp.com/en/1.2.6/reference/models.html#events-and-events-manager
发布于 2016-04-05 07:48:59
我想使用CRUD的表单,因为它们非常动态和可重用。您可以使用选项在表单中实现这一点。
您可以传递其他选项,以形成和执行类似场景的操作。
您可以在这里检查表单构造函数。
在控制器中,您可以传递$options。
<?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function insertAction()
{
$options = array();
$options['scenario'] = 'insert';
$myForm = new MyForm(null, $options);
if($this->request->hasPost('insert')) {
// this will be our model
$profile = new Profile();
// we will bind model to form to copy all valid data and check validations of forms
if($myForm->isValid($_POST, $profile)) {
$profile->save();
}
else {
echo "<pre/>";print_r($myForm->getMessages());exit();
}
}
}
public function updateAction()
{
$options = array();
$options['scenario'] = 'update';
$myForm = new MyForm(null, $options);
}
}你的表格应该看起来像这样
<?php
// elements
use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Text;
// validators
use Phalcon\Validation\Validator\PresenceOf;
class MyForm extends Form {
public function initialize($entity = null, $options = null) {
$name = new Text('first_name');
$this->add($name);
if($options['scenario'] == 'insert') {
// at the insertion time name is required
$name->addValidator(new PresenceOf(array('message' => 'Name is required.')));
}
else {
// at the update time name is not required
// as well you can add more additional validations
}
}
}现在,您可以添加多个场景并根据场景执行操作。
https://stackoverflow.com/questions/22500808
复制相似问题