Respect / Validation

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

Validation with v::when not working #1470

Open slashforward-nl opened 3 weeks ago

slashforward-nl commented 3 weeks ago

I have the following code:

try {
  $result = v::key(
    'textblok1', 
    v::when(
      v::key('radiobutton', v::equals('textblok1')),
      v::notEmpty()
    )
  )->assert($this->postData);
} catch (NestedValidationException $e) {
  print_r($e->getMessages());
}

$this->postData contains the following array:

Array
(
    [radiobutton] => textblok2
    [textblok1] => test
    [textblok2] => 
)

But i get the following error: Array ( [textblok1] => "test" is not valid )

What am i doing wrong?

Thanks in advance!

Wouter

andus4n commented 2 weeks ago

when using nested conditions you're basically passing the previously checked value to the nested rules. so, in your example, the engine is checking if "textblok1" is an array with the key "radiobutton" that should equal "textblok1", therefore it fails. i'm guessin' you want somethin' like this:

v::when
(
   v::key('radiobutton', v::equals('textblok1')),
   v::key('textblok1', v::notEmpty()),
   v::alwaysValid()
)
slashforward-nl commented 2 weeks ago

Thank you for your suggestion, too bad i get the same with this:

$result = v::key(
  'textblok1', 
  v::when(
    v::key('radiobutton', v::equals('textblok1')),
    v::key('textblok1', v::notEmpty())
  )
)->assert($this->postData);

Array
(
    [radiobutton] => textblok1
    [textblok1] => testtest
    [textblok2] => 
)

Array ( [textblok1] => "testtest" is not valid ) 

In this case radiobutton equals textblok1, so textblok1 field should not be empty. And its not in our case. Any suggestions?

andus4n commented 2 weeks ago

Please read my comment thoroughly. The proper validation rule for your scenario is:

v::when
(
   v::key('radiobutton', v::equals('textblok1')),
   v::key('textblok1', v::notEmpty()),
   v::alwaysValid() // assuming all other scenarios are acceptable
)
->assert($this->postData);

Of course, you should add extra rules like first validating that "postData" is an array etc etc

slashforward-nl commented 2 weeks ago

Ah i thought i could do the v::when in a v::key so i could add rules based on the v::when.

Textbox rule (if radiobutton = textblok1) then notEmpty else alwaysValid. Textbox2 rule (if radiobutton = textblok2) then notEmpty else alwaysValid.

I will check ik out, thanks for your help

andus4n commented 2 weeks ago

c0