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:
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:
In this example:
example_fieldis a simple string field.- We use the
@validatesdecorator on thevalidate_example_fieldfunction to indicate that it validates theexample_field. - The function checks a condition and raises a
ValidationErrorif 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).
- In the code above we define a custom validator for the
usernamefield using the@validatesdecorator. - The
validate_usernamemethod performs multiple checks by chainingifstatements. It first checks if theusernameis at least three characters long, and then checks if it contains only alphanumeric characters. - If the
usernamefails any of these checks, aValidationErroris raised with an appropriate error message.
