Marshmallow-Based User Data Validation Function

  • Share this:

Code introduction


This function uses the Marshmallow library to validate user input data to ensure it conforms to expected formats and types.


Technology Stack : Marshmallow

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
from marshmallow import Schema, fields, ValidationError

def validate_user_data(data):
    # Define a Marshmallow schema for user data validation
    class UserSchema(Schema):
        username = fields.Str(required=True)
        email = fields.Email(required=True)
        age = fields.Int(validate=lambda x: 0 <= x <= 120)

    # Create an instance of the schema
    user_schema = UserSchema()
    
    # Try to load the data into the schema and validate it
    try:
        user = user_schema.load(data)
        return {"message": "Validation successful", "data": user}
    except ValidationError as err:
        return {"message": "Validation failed", "errors": err.messages}

# Code Explanation
# This function takes a dictionary containing user data and validates it using a Marshmallow schema.
# The schema defines the structure of the data and the types of fields (e.g., string, integer, email).
# The function returns a dictionary indicating whether the validation was successful or not, and in case of failure, it provides the validation errors.

# JSON Explanation                
              
Tags: