Skip to content

Instantly share code, notes, and snippets.

@matt-allan
Last active January 20, 2016 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matt-allan/d2fc36fad599bfeedb0b to your computer and use it in GitHub Desktop.
Save matt-allan/d2fc36fad599bfeedb0b to your computer and use it in GitHub Desktop.
Implicit Validation For Lumen

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": []
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment