简体   繁体   中英

Phalcon PHP custom validation rule raise an error

I'm using Phalcon framework, and I'm trying to make a custom validator:

<?php    
use Phalcon\Validation\Validator,
    Phalcon\Validation\ValidatorInterface,
    Phalcon\Validation\Message;

class Currency extends Validator implements ValidatorInterface
{

    /**
     * Executes the validation
     *
     * @param Phalcon\Validation $validator
     * @param string $attribute
     * @return boolean
     */
    public function validate($validator, $attribute)
    {
        $value = $validator->getValue($attribute);

        if(! is_numeric($value))
        {
            $message = $this->getOption('message');
            if(! $message){
                $message = 'Not a valid currency.';
            }

            $validator->appendMessage(new Message($message, $attribute, 'Currency'));

            return false;
        }

        return true;
    }

}

I get this error when trying to use the validator above:

Unexpected value type: expected object implementing Phalcon\\Mvc\\Model\\ValidatorInterface, object of type Currency given

I put the validator class in /plugins/validators/Currency.php and auto-loaded it of course using DI. Any clues?

this kind of validator cannot be used on model validation. " Phalcon\\Validation is an independent validation component that validates an arbitrary set of data. This component can be used to implement validation rules on data objects that do not belong to a model or collection. "

more info here: http://docs.phalconphp.com/en/latest/reference/validation.html#validators

for model validators you need to use another interface.

info here:

http://docs.phalconphp.com/en/latest/reference/models.html#validating-data-integrity

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM