DEV Community

elifrie
elifrie

Posted on

Validators in Flask

As you begin to create and manage databases it's important to keep in mind that the type of data you are allowing users to input can have large effects on your databases. Validators are used to do just that; maintain the integrity of the data flowing into your databases.

You must imagine every possible edge case for how a user will interact with your webpage and then utilize validators to protect against those cases.

Using validators is generally very intuitive and basic.

Within your models and class definitions on the back-end you can define validators as so:

class User(db.Model, SerializerMixin):
   __tablename__ = 'users'

   ##here all your relationships will lie##


   ###below you are defining what variable you will be validating.##
   @validates('username'):
   ##creating a validation##
   def validate_username(self, key, value):
      if not value:
           raise ValueError('Please enter a username')
   ##forcing a user to enter a value for their username to proceed, otherwise they will see a value error##
      return value
   ##returning the value if a username is provided by the user##
Enter fullscreen mode Exit fullscreen mode

Above is an example of how you would do a simple validation for one variable. You'll notice I passed through 'value' rather than 'username' and checked against value. The reason for that is so you can check multiple variables if they require the same validation. The example below is how you would force a user to input a value for both username and email.

class User(db.Model, SerializerMixin):
   __tablename__ = 'users'

   ##here all your relationships will lie##

   @validates('username', 'email'):
   def validate_username(self, key, value):
      if not value:
           raise ValueError('Please enter a username')
      return value
Enter fullscreen mode Exit fullscreen mode

At the end of the day validating isn't too daunting and it's something that is important to implement upfront to save you time on the back-end haha ;).

Top comments (0)