We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Custom Validator

Hi,

I would like to create a custom validator. In addition to the field value, I would like to add an other value to compare with. I don't know how to do it and it's not explained in the doc.

Could you help me ?

Thanks.

Do you perhaps mean something like the ConfirmationOf validator in the Phalcon Incubator Repo?

If you want to compare it to a value defined serverside i think you can get it to work with small changes in the code



3.1k

Thank you for your answer but your example is for Model/Validatior. I would like an example for Validation/Validator.



3.1k
edited Mar '15

Could you tell me why this code doesn't work. It doesn't raise exception, It just stops and does nothing.

https://pastebin.com/ZsFgYAKR

That looks good to me. I just setup and tested it in a simple form and it looks ok to me

<?php
// Form is a simple <input type=text name=test> form
if($this->request->isPost()) {
    $validation = new Phalcon\Validation();

    $validation->add('test', new CheckPassword(array(
        'value' => 'foo' // has of expected password
    )));

    $messages = $validation->validate($this->request->getPost());

    if(count($messages)) {
        // Validation failed here
    }
}

Your validator will not raise an error itself, Phalon\Validation will take care of that when you call $validation->validate();



3.1k

It's weird because when I launch a debug, the debug stops at $validation->add('current', new CheckPassword(array( 'value' => 'password', 'message' => 'message to show to user' )))



3.1k
edited Mar '15

Problem solved.

The problem came from two points.

1)

<?php
public function validate(Validation $validator, $field) // is not right. 
public function validate($validator, $field) // It must be this even if my IDE highlights $validator 

2)

<?php
// The class wasn't registered. I had to use $loader->registerNamespaces() and to include the path to directory of my custom validators directory.
$loader->registerNamespaces(
  array(
    'Phalcon\Validation\Validator'  => '../app/validators/'
  )
);


3.1k

Can anyone tell me why markdown doesn't work for me ?



718
Accepted
answer

Can anyone tell me why markdown doesn't work for me ?

Empty line before "```php" will help



3.1k

Thanks a lot !