Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Phalcon Validation

I want to validate some parameter in my code, I wanna be sure that params value is an integer. I know that in Phalcon I have build in mechanism that allow me to validate params.

e.g:

class NumberValidator extends Validation
{
    public function initialize()
    {
        $this->add('number', new RegexValidator(
                array(
                    'pattern' => '^[0-9]+$',
                    'message' => 'Should be an integer number.'
                )
            )
        );
    }
}

now if I want validate that my variable $number is a number I should execute:

$numberVal = new Validators\NumberValidator();
$numberVal->validate(array('number' => $myParam));

My question is: Is there a way to validate only the parameter value without providing a parameter name. For example, if I want to be sure that the value of my parameter (any parameter) is integer I will execute:

<?php

$numberVal = new Validators\NumberValidator();
$numberVal->validate($myParam);


83.0k
Accepted
answer
edited Jul '14

You can create a plain class to do that:

namespace Validators;

class NumberValidator
{
    public function validate($value)
    {
        return is_numeric($value);
    }
}

However, If you plan to use this validator among Phalcon\Validation, the validator needs to know which field must be validated:

<?php

namespace Validators;

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

class NumberValidator 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)) {
            $validator->appendMessage(new Message('The number is not valid', $attribute, 'Number'));
            return false;           
        }
        return true;
    }

}

how the source code to set autoincrement in the framework Phalcon ..?? :D