Skip to content

Commit

Permalink
Add NotIn validation
Browse files Browse the repository at this point in the history
Relatively self explanitory, this is a valdiator that ensures values
are not in a given collection of values, e.g.

    schema = Schema({"color": NotIn(frozenset(["blue", "red", "yellow"]))})
    schema({"color": "orange"})  # valid
    schema({"color": "blue"})  # invalid
  • Loading branch information
petedmarsh committed Jan 20, 2016
1 parent 6dee4ec commit f2241ce
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
14 changes: 13 additions & 1 deletion tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import voluptuous
from voluptuous import (
Schema, Required, Extra, Invalid, In, Remove, Literal,
Url, MultipleInvalid, LiteralInvalid
Url, MultipleInvalid, LiteralInvalid, NotIn
)


Expand Down Expand Up @@ -46,6 +46,18 @@ def test_in():
schema({"color": "blue"})


def test_not_in():
"""Verify that NotIn works."""
schema = Schema({"color": NotIn(frozenset(["blue", "red", "yellow"]))})
schema({"color": "orange"})
try:
schema({"color": "blue"})
except Invalid as e:
assert_equal(str(e), "value is not allowed for dictionary value @ data['color']")
else:
assert False, "Did not raise NotInInvalid"


def test_remove():
"""Verify that Remove works."""
# remove dict keys
Expand Down
18 changes: 18 additions & 0 deletions voluptuous.py
Original file line number Diff line number Diff line change
Expand Up @@ -1584,6 +1584,24 @@ def validator(value):
return validator


class NotInInvalid(Invalid):
pass


def NotIn(container, msg=None):
"""Validate that a value is not in a collection."""
@wraps(NotIn)
def validator(value):
try:
check = value in container
except TypeError:
check = True
if check:
raise NotInInvalid(msg or 'value is not allowed')
return value
return validator


def Lower(v):
"""Transform a string to lower case.
Expand Down

0 comments on commit f2241ce

Please sign in to comment.