Skip to content

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

@piotr-cz

Description

@piotr-cz

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions