Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to create validator that allows either null or an integer? #378

Open
piotr-cz opened this issue Jun 20, 2024 · 0 comments
Open

How to create validator that allows either null or an integer? #378

piotr-cz opened this issue Jun 20, 2024 · 0 comments

Comments

@piotr-cz
Copy link
Contributor

How to test that array of data:

  • contains given key
  • key is either null or an integer?
// Case 1: Passes when key is missing
$v = new \Valitron\Validator([]);
$v->mapFieldRules('id', ['optional', 'integer']);

$v->validate(); // true
$errors = $v->errors(); // []


// Case 2: Fails for null
$v = new \Valitron\Validator(['id' => null]);
$v->mapFieldRules('id', ['required', 'integer']);

$r = $v->validate(); // false
$errors = $v->errors(); // ['id' => ['Id required', 'Id integer']]


// Case 3: Fails for null
$v = new \Valitron\Validator(['id' => null]);
$v->mapFieldRules('id', [['required', true], 'integer']);

$r = $v->validate(); // false
$errors = $v->errors(); // ['id => ['Id integer']];

I've tried creating custom validator but with no luck

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant