currently I am using marshmallow schema to validate the request, and I have this a list and I need to validate the content of it.
class PostValidationSchema(Schema):
checks = fields.List(
fields.String(required=True)
)
the checks field is a list it should only contain these specific values ["booking", "reservation", "flight"]
If you mean to check the list only has those three elements in that order, then use Equal
validator.
from marshmallow import Schema, fields, validate
class PostValidationSchema(Schema):
checks = fields.List(
fields.String(required=True),
validate=validate.Equal(["booking", "reservation", "flight"])
)
schema = PostValidationSchema()
schema.load({"checks": ["booking", "reservation", "flight"]}) # OK
schema.load({"checks": ["booking", "reservation"]}) # ValidationError
If the list can have any number of elements and those can only be one of those three specific values, then use OneOf
validator.
from marshmallow import Schema, fields, validate
class PostValidationSchema(Schema):
checks = fields.List(
fields.String(
required=True,
validate=validate.OneOf(["booking", "reservation", "flight"])
),
)
schema = PostValidationSchema()
schema.load({"checks": ["booking", "reservation", "flight"]}) # OK
schema.load({"checks": ["booking", "reservation"]}) # OK
schema.load({"checks": ["booking", "dummy"]}) # ValidationError
In addition to Jerome answer, I also figured out that if you need to do something which requires more logic you could do:
def validate_check(check: str):
return check in ["booking", "reservation", "flight"]
class PostValidationSchema(Schema):
checks = fields.List(
fields.String(required=True, validate=validate_check)
)
Or using lambda:
class PostValidationSchema(Schema):
checks = fields.List(
fields.String(required=True, validate=lambda check: check in ["booking", "reservation", "flight"])
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With