Skip to content

Add support for optional strict type validation #392

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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion jsonschema/_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,8 +286,27 @@ def extends_draft3(validator, extends, instance, schema):

def type_draft4(validator, types, instance, schema):
types = _utils.ensure_list(types)
pass_strict_validation = any(validator.is_type(instance, type) for type in types)

if not any(validator.is_type(instance, type) for type in types):
if validator.strict_validation:
if not pass_strict_validation:
yield ValidationError(_utils.types_msg(instance, types))
return

is_int = is_float = False
if 'integer' in types:
try:
is_int = any(validator.is_type(int(instance), type) for type in types)
except (ValueError, TypeError):
pass

if 'number' in types:
try:
is_float = any(validator.is_type(float(instance), type) for type in types)
except (ValueError, TypeError):
pass

if not pass_strict_validation and not is_int and not is_float:
yield ValidationError(_utils.types_msg(instance, types))


Expand Down
2 changes: 2 additions & 0 deletions jsonschema/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ def __init__(
types=(),
resolver=None,
format_checker=None,
strict_validation=True,
):
if types:
warn(
Expand All @@ -233,6 +234,7 @@ def __init__(
self.resolver = resolver
self.format_checker = format_checker
self.schema = schema
self.strict_validation = strict_validation

@classmethod
def check_schema(cls, schema):
Expand Down