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

Form addValidators with condition

Is there way to validate form with conditions? I know I could add a custom valiadator, but I wonder if there is other ways


//* password
        $password = new Password('password', ['autocomplete'=>"off",'placeholder'=>'Password']);
        $password->addValidators(array(
            new StringLength(array(
                'min' => 8,
                'messageMinimum' => 'Password is too short. Minimum 8 characters'
            )),
        ));
        $this->add($password);

This is the part of form I used to validate password, I also use it on edit password page, so empty password will be allowed that means user is intend to the password.

is there anything I can use to trigger the validate only when password is not empty?

I prefer regular expression over this.

<?php

use Phalcon\Validation;
use Phalcon\Validation\Validator\Regex;

class PasswordValidation extends Validation
{
    public function initialize()
    {
        $this->add('password', new Regex(array(
            'pattern' => '/.+/',
            'message' => 'Password is not empty.',
        )));
    }
}

And check password minimum 8 charectors is /.{8}/



34.6k
Accepted
answer

This way:

$password = new Password('password', ['autocomplete'=>"off",'placeholder'=>'Password']);
$password->addValidators(array(
    new StringLength(array(
            'min' => 8,
            'messageMinimum' => 'Password is too short. Minimum 8 characters',
            'allowEmpty' => true
    )),
));
$this->add($password);