Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate list in marshmallow

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"]

like image 392
Jann Anthony Briza Avatar asked Dec 22 '22 19:12

Jann Anthony Briza


2 Answers

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
like image 76
Jérôme Avatar answered Jan 03 '23 05:01

Jérôme


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"])
    )

like image 41
Jann Anthony Briza Avatar answered Jan 03 '23 05:01

Jann Anthony Briza