Respect / Validation

The most awesome validation engine ever created for PHP
https://respect-validation.readthedocs.io
MIT License
5.76k stars 774 forks source link

Add more rules if some condition is met #1372

Closed liviuhariton closed 2 years ago

liviuhariton commented 2 years ago

Hi everyone! I try to find the proper logic to add some more rules on a previous rules set (that was already defined) if some condition is met.

`$form_validation_rules = v::key('password_current', v::length(6)) ->key('password', v::length(6)) ->key('password_confirm', v::length(6)) ->equals($_POST['password'])->validate('password_confirm');

    if($this->admin_role->owner === 1) {
        $form_validation_rules->key('username', v::length(3))->key('username', v::alnum());
    }`

In the above, the first set of rules is set and, if the _$this->adminrole->owner === 1 condition is met, add some more rules. The output is Error: Call to a member function key() on bool

My question is: how can I extend an already set of rules later on, in code (based on various logic conditions) ?

thank you in advance!

liviuhariton commented 2 years ago

Nevermind :) My code logic was wrong. This is the working way:

` $form_validation_rules = v::key('password_current', v::length(6)) ->key('password', v::length(6)) ->keyValue('password_confirm', 'equals', 'password');

    if($this->admin_role->owner === 1) {
        $form_validation_rules->key('username', v::length(3))->key('username', v::alnum());
    }

`

In my initial version, the equals() usage was wrong. Also, the keyValue() method saves time :)

alganet commented 2 years ago

Glad you got it working! Let us know if you need help with anything else