Marshmallow Data Validation Function

  • Share this:

Code introduction


The function uses the Marshmallow library to validate incoming data against a predefined schema. If the data validation passes, the function returns True, otherwise it returns False.


Technology Stack : Marshmallow

Code Type : Custom function

Code Difficulty : Intermediate


                
                    
from marshmallow import Schema, fields, ValidationError

def validate_data(data):
    # Define a schema for the data
    class UserSchema(Schema):
        name = fields.Str(required=True)
        age = fields.Int(required=True, validate=lambda x: x > 0)

    # Create an instance of the schema
    schema = UserSchema()

    # Try to load the data, this will raise an error if the data does not validate
    try:
        schema.load(data)
        return True
    except ValidationError as err:
        return False

# JSON representation of the code                
              
Tags: