vlucas/valitron

Question: RequiredWithout with Optional

Opened this issue · 1 comments

Hi!

I can't get my head around a validation I am trying to archive.

Let's take the example from the README where you can conditionally require values using required conditional rules:

// this rule set would work for either data set...
$data = ['email' => 'test@test.com', 'password' => 'mypassword'];
// or...
$data = ['token' => 'jashdjahs83rufh89y38h38h'];

$v = new Valitron\Validator($data);
$v->rules([
    'requiredWithout' => [
        ['token', ['email', 'password'], true]
    ],
    'requiredWith' => [
        ['password', ['email']]
    ],
    'email' => [
        ['email']
    ],
    'optional' => [
        ['email']
    ]
]);
$this->assertTrue($v->validate());

Lets say I want to add a rule to the token entry. For example I want to check if the token only contains AlphaNum values.
I would do it like this:

// this rule set would work for either data set...
$data = ['email' => 'test@test.com', 'password' => 'mypassword'];
// or...
$data = ['token' => 'jashdjahs83rufh89y38h38h'];

$v = new Valitron\Validator($data);
$v->rules([
    'requiredWithout' => [
        ['token', ['email', 'password'], true]
    ],
    'requiredWith' => [
        ['password', ['email']]
    ],
    'alphaNum' => [
       ['token']
    ],
    'email' => [
        ['email']
    ],
    'optional' => [
        ['email', 'token']
    ]
]);
$this->assertTrue($v->validate());

I add the rule 'alphaNum' to check if the token only contains alphanumerical values. I also add the 'token' to the 'optional' rule, because my intention is to check the token only if its exists.

But when I run the above code with 'email' and 'token' as data I always get the following error:

array(1) {
  ["token"]=>
  array(1) {
    [0]=>
    string(54) "Token must contain only letters a-z and/or numbers 0-9"
  }
}

Am I doing something wrong or is this kind of validation not possible?

Thank you for your help!

Alex

Possible related to #304