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!
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.
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_field
is a simple string field.- We use the
@validates
decorator on thevalidate_example_field
function to indicate that it validates theexample_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.
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
username
field using the@validates
decorator. - The
validate_username
method performs multiple checks by chainingif
statements. It first checks if theusername
is at least three characters long, and then checks if it contains only alphanumeric characters. - If the
username
fails any of these checks, aValidationError
is raised with an appropriate error message.
Next, let's create a custom validator for the email
field. This validator will ensure that email addresses belong to a specific domain, @example.com
.
- Here we define a custom validator for the
email
field using the@validates
decorator. - The
validate_email
method checks if theemail
value ends with the domain@example.com
. - If the
email
does not meet this condition, aValidationError
is raised with an error message specifying the requirement.
When a validation error occurs, the response will indicate the specific reasons for the failure. For example:
In this lesson, we learned how to build custom validators using Marshmallow in a Flask application. We started with a basic setup, then created a custom validator for the username field to ensure it is at least three characters long and alphanumeric. We also developed a custom validator for the email field to ensure the email addresses belong to the specific domain @example.com
. By integrating these custom validators into our schema, we can enforce specific business rules and data integrity.
Now, it's your turn to practice creating and validating custom fields in the upcoming exercises. Keep experimenting and happy coding!
