Building Your Own Custom Validator

Building Your Own Custom Validator

Welcome back! In this lesson, we will focus on building custom validators to handle specific data validation needs that built-in validators in Marshmallow may not cover. By creating custom validators, you can enforce business rules and data integrity specific to your application.

Let's get started!

Basic Setup

Before we dive into custom validators, let's briefly recap our basic Flask setup using a mock database:

from flask import Flask, request, jsonify
from marshmallow import Schema, fields, ValidationError

# Initialize a Flask app instance
app = Flask(__name__)

# Mock database as a list of dictionaries
database = [
    {"id": 1, "username": "cosmo", "email": "cosmo@example.com"},
    {"id": 2, "username": "jake", "email": "jake@example.com"},
    {"id": 3, "username": "emma", "email": "emma@example.com"}
]

# Define a User schema
class UserSchema(Schema):
    id = fields.Int()
    username = fields.Str(required=True)
    email = fields.Email(required=True)

Now, we are ready to define and use custom validators.

Custom Validators with Marshmallow

Marshmallow allows us to create custom validators using the @validates decorator. This decorator is applied to a function within your schema that will validate a specific field. If the value doesn’t meet the criteria, the function raises a ValidationError.

Here is a generic example:

from marshmallow import Schema, fields, validates, ValidationError

class ExampleSchema(Schema):
    example_field = fields.Str()

    @validates('example_field')
    def validate_example_field(self, value):
        if value != 'expected_value':  # Example condition
            raise ValidationError('Value must be ...')

In this example:

  • example_field is a simple string field.
  • We use the @validates decorator on the validate_example_field function to indicate that it validates the example_field.
  • The function checks a condition and raises a ValidationError if the condition is not met.

Let’s now create custom validators for our specific use case.

Creating a Custom Validator for the Username Field

Let's start by building a custom validator for the username field. This validator will ensure that the username is at least three characters long and contains only alphanumeric characters (letters and numbers).

from marshmallow import validates

class UserSchema(Schema):
    id = fields.Int()
    username = fields.Str(required=True)
    email = fields.Email(required=True)
    
    # Custom validator for the username field
    @validates('username')
    def validate_username(self, value):
        if len(value) < 3:
            raise ValidationError('Username must be at least 3 characters.')
        if not value.isalnum():
            raise ValidationError('Username must contain only letters and numbers.')
  • In the code above we define a custom validator for the username field using the @validates decorator.
  • The validate_username method performs multiple checks by chaining if statements. It first checks if the username is at least three characters long, and then checks if it contains only alphanumeric characters.
  • If the username fails any of these checks, a ValidationError is raised with an appropriate error message.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal