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.

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}/



33.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);