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_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.
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.
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
emailfield using the@validatesdecorator. - The
validate_emailmethod checks if theemailvalue ends with the domain@example.com. - If the
emaildoes not meet this condition, aValidationErroris 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!
