Search code examples
python-3.xunit-testingvalidationmarshmallow

How to add multiple validation parameters in a marshmallow schema


I have the following schema in one of my class models:

class SocialMediaSchema(Schema):
    facebook_profile_url = fields.String(required=False, validate=validate.Length(0, 71, 'Facebook username is too long.')

Aside from validating the length, I also want to be able to make sure that facebook_profile_url is never equal to the string "http://www.facebook.com/".


Solution

  • You can pass a list as the validate parameter:

    class SocialMediaSchema(Schema):
        facebook_profile_url = fields.String(required=False, validate=[
            validate.Length(0, 71, 'Facebook username is too long.'),
            lambda x: x != "http://www.facebook.com/"
        ])
    

    From the documentation:

    validate (callable) – Validator or collection of validators that are called during deserialization.