Currently the validator will not run validation rules for empty values:
$rules = ['age' => 'integer'];
$input = json_decode('{"age": null}', true);
Validator::make($input, $rules)->passes(); // true
When validating JSON, this results in clumsy and awkward rules to prevent null values:
$rules = ['age' => 'sometimes|required|integer'];
$input = json_decode('{"age": null}', true);
Validator::make($input, $rules)->passes(); // false
When writing my JSON validation rules I need to:
- prefix with
sometimes|required
if it cannot be null but isn't required. - prefix with
required
if it cannot be null and is required. - not prefix the rule if it can be null and is not required.
IMO this makes the logic hard to reason about. When writing a JSON API, the key is only present if the user sent it. I think it makes more sense for Lumen's validator to be implicit be default:
$rules = ['age' => 'integer'];
$input = json_decode('{"age": null}', true);
Validator::make($input, $rules)->passes(); // false
If you want to allow null, you need to do so explicitly:
$rules = ['age' => 'integer|null'];
$input = json_decode('{"age": null}', true);
Validator::make($input, $rules)->passes(); // true
This is more inline with how you would write a JSON schema:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "User",
"description": "A user of my app",
"type": "object",
"properties": {
"id": {
"description": "The user's age",
"type": ["number", "null"]
},
},
"required": []
}