Search code examples
pythonmarshmallow

Python Marshmallow condition based validation


This is my code

from marshmallow import Schema, fields,ValidationError,INCLUDE


class userschema(Schema):
    name = fields.String()
    gender = fields.String()
    age = fields.Integer(validate=Range(min=18, max=100))

def user_check(user):
    try:
        validate = userschema().load(user,unknown=INCLUDE)
        print(validate)
    except ValidationError as err:
        print(err.messages)


user_1 = {"name":"priya","gender":"female","age":20}
user_2 = {"name":"gowtham","gender":"male","age":50}

user_check(user_1)

Is there any way to validate the age for male required minimum of 21 and for female minimum of 18


Solution

  • The validator you have used (validate.Range). It will validate for each user both male and female. For your case you need a custom validator function. Use something like this.

    # other imports
    from marshmallow import validates_schema
    
    class UserSchema(Schema):
        name = fields.String()
        gender = fields.String()
        age = fields.Integer()
        
        @validates_schema
        def validate_age(self, data, **kwargs):
            if data['gender'] == 'male':
                if data['age'] < 21:
                    raise ValidationError("Minimum age for males is 21.")
    
            if data['gender'] == 'female':
                if data['age'] < 18:
                    raise ValidationError("Minimum age for females is 18.")
    

    References: https://marshmallow.readthedocs.io/en/latest/extending.html#schema-level-validation