Marshmallow-Based User Data Validation

  • Share this:

Code introduction


This function uses the Marshmallow library to validate user data, including username length, email format, and age restrictions.


Technology Stack : Marshmallow

Code Type : Validation Function

Code Difficulty : Intermediate


                
                    
from marshmallow import Schema, fields, ValidationError

def validate_user_data(data):
    """
    Validates user data using Marshmallow.
    """
    class UserSchema(Schema):
        username = fields.Str(required=True, validate=lambda s: len(s) > 5)
        email = fields.Email(required=True)
        age = fields.Int(validate=lambda x: x > 18)

    try:
        user_schema = UserSchema()
        user = user_schema.load(data)
        return {"message": "Data is valid.", "user": user}
    except ValidationError as err:
        return {"message": "Data is invalid.", "errors": err.messages}

# JSON representation of the function                
              
Tags: