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

«Or Null» validator

Hello,

Is it possible to add validator like «Or Null» to Form field validators? I have a Form with field which may have an empty value, but if a value is present, it should be checked by validators.



98.9k

I am not sure if this is what you need but maybe this could help you

https://docs.phalcon.io/en/latest/reference/validation.html#validation-cancelling

I need something like «cancelOnSuccess» :)

My decision:

class EmptyValidator extends Validator implements ValidatorInterface
{

    /**
     * @var \Phalcon\Validation\ValidatorInterface[]
     */
    protected $validators;

    /**
     * @param \Phalcon\Validation\ValidatorInterface[] $validators
     */
    public function __construct($validators = null)
    {
        $this->validators = $validators;
    }

    /**
     * @param Validation $validator
     * @param string $attribute
     *
     * @return boolean
     */
    public function validate($validator, $attribute)
    {
        $value = $validator->getValue($attribute);
        $result = true;

        if (!empty($value)) {
            if (!empty($this->validators) && sizeof($this->validators)) {
                /**
                 * @var \Phalcon\Validation\ValidatorInterface $_validator
                 */
                foreach ($this->validators as $_validator) {
                    $validationResult = $_validator->validate($validator, $attribute);

                    if (!$validationResult) {
                        $result = false;
                    }
                }
            }
        }

        return $result;
    }

}

And using:

        $email->addValidators([new EmptyValidator([
            new EmailValidator([
                'message' => 'Email is invalid',
            ]),
        ])]);


13.8k

Hellо, i'm use your code with regex validator and get this error

Warning: preg_match(): Compilation failed: range out of order in character class at offset 8 in E:\www\domains\localhost3\app\library\EmptyValidator.php on line 41

I guess the problem is in but i think what return exception will be better. how add exception in this code?)))