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

SOLVED - Custom Validator Not working

Good night, why is this custom validator is not workink, it calls the function validate($validator, $attribute) return false, but the form isValid() still return true

I have to register in any place?

Thanks Good Night code below

Code at paste bin : https://pastebin.com/vPY69afH

......

use Phalcon\Validation\Validator, Phalcon\Validation\ValidatorInterface, Phalcon\Validation\Message;

class DbNoRecordExists extends Validator implements ValidatorInterface { public function validate($validator, $attribute) { $valid = ( $find->count() ) ? false : true; return $valid; } }

$slug = new Text("slug");

$slug->addValidator(new DbNoRecordExists(array( 'db' => 'paginas', 'message' => 'Slug já cadastrado', )));

$slug->addValidator(new PresenceOf(array( 'message' => 'The slug is required' )));

$slug->addValidator(new StringLength(array( 'min' => 3, 'messageMinimum' => 'The slug is too short' )));

$this->add($slug);



2.1k

where do you get $find

its just a part of the code, find is a query valid return a bool true or false the form calls the function

Full Code https://pastebin.com/uXtzb7Fu



2.1k
edited Jan '15

i see you do have a model for the object. if that is the case couldnt you just do

   public function validate($validator, $attribute)
    {
        $modelName = '\Apps\Backend\Models\\'.ucfirst($this->getOption('db'));
        $modelObj = new $modelName; // or was it $$modelName;
        $value = $validator->getValue($attribute);
        $field = ( $this->isSetOption('field') ) ? $this->getOption('field') : $attribute;
        $attr = sprintf("%s = '%s'", $field, $value);
        return $modelObj->count($attr) > 0;
    }

either or. something similar. havent tested it but i believe you can do this too

    public function validate($validator, $attribute)
    {
        $modelObj = new ReflectionClass('\Apps\Backend\Models\\'.ucfirst($this->getOption('db')));
        $value = $validator->getValue($attribute);
        $field = ( $this->isSetOption('field') ) ? $this->getOption('field') : $attribute;
        $attr = sprintf("%s = '%s'", $field, $value);
        return $modelObj->count($attr) > 0;
    }

or you can invoke the static functions somehow. wonder if you could do

$modelName::count($attr)

https://docs.phalcon.io/en/latest/api/Phalcon_Mvc_Model.html

or you can use the one that is already available to you

https://docs.phalcon.io/en/latest/api/Phalcon_Mvc_Model_Validator_Uniqueness.html

you can use that in a form too u just have to set the model name if i am not wrong =)



9.7k
Accepted
answer

Ok i found the error i forgot to use $validator->appendMessage(new Message(sprintf('%s : Já existe um registro "%s" ',$field, $value), $attribute, 'IsAwesomeDate'));

its workinkg now thanks!