Reputation: 1569
Phalcon support 2 validation components:
Phalcon\Validation\Validator
Phalcon\Mvc\Model\Validator
I dont know how to use them in my situation. I have a registration form with:
I created a registration form as following:
class RegistrationForm extends \Phalcon\Forms\Form
{
public function initialize()
{
$csrf = new \Phalcon\Forms\Element\Hidden('csrf');
$csrf->addValidator(new \Phalcon\Validation\Validator\Identical(array(
'value' => $this->security->getSessionToken(),
'message' => 'CSRF validation failed'
)));
$username = new \Phalcon\Forms\Element\Text('username');
$username->addFilter('trim');
$username->addValidator(new PresenceOf(array(
'message' => 'Username is required.',
)));
$username->addValidator(new StringLength(array(
'min' => 6,
'messageMinimum' => 'Username must be at least 6 characters.'
)));
// ...
}
}
And this is my controller/action:
class UserController extends \Phalcon\Mvc\Controller
{
public function registerAction()
{
$form = new RegistrationForm();
if ($this->request->isPost()) {
if ($form->isValid($this->request->getPost())) {
// Test only
var_dump($this->request->getPost());
exit;
} else {
// Test only
foreach ($form->getMessages() as $message) {
echo $message, '<br/>';
}
exit;
}
}
$this->view->form = $form;
}
}
Thank for your help!
Upvotes: 3
Views: 10224
Reputation: 9085
You use model validator before sending your data to the database. Often, the data (type / structure / hierarchy) in your POST and in your model would differ, for example, a single form receives input related to two models, both of which will be updated. So, upon receiving POST data you want to check that it's valid, and upon saving two independent models, you want also to check that they are valid.
Phalcon has a validation component, which is a base class for all validation. It works in exactly the same way as the form validation in your code above.
I'm not a big fan of how the whole validation business is implemented in Phalcon – it doesn't give you a grain-level of control and there's a strong dependency between validation and validators. Yet, it does good work in the scope of form and model validation. There's no neat or tidy way of reusing the same validators, but there are some know attempts, you can use your imagination :)
To implement your register action you only should use your form validator to filter out the user input. I might be wrong, but Phalcon models automatically validate data based on the metadata on the fields, so all you need to worry is your POST input. Big working with models documentation covers that subject in detail, I'm sure you've already been there.
Upvotes: 4