DEV Community

arnu515
arnu515

Posted on

Form validation in python made #EZ (By Yours Truly)

After looking at an NPM library called joi, I was amazed at what it could do and how it could make your javascript form validation easy.

I was also disappointed that a similar library didn't exist for python that was framework independant, so I created one!

Welcome to DontTrust

DontTrust is a python form validation library that is inspired by joi. It is similar to joi, but it does lack a bit in features. Before we look at its features, we have to install it:

pip install donttrust
Enter fullscreen mode Exit fullscreen mode

Schemas

Schemas are what define a field in your form. There are 6 types of schemas currently:

  • string
  • number (includes int, float and complex)
  • email
  • date
  • boolean
  • any type

To initialise a schema:

from donttrust import Schema

username_field = Schema("username")
Enter fullscreen mode Exit fullscreen mode

The "username" parameter in Schema is optional, but it is recommended because error messages will be formatted with it.

To create a schema of a specific type,

username_field = Schema("username").string()
# or .number(), .boolean(), .email(), etc
Enter fullscreen mode Exit fullscreen mode

Validate a schema

There are two ways to validate a schema:

# With an exception
from donttrust import Schema
from donttrust.exceptions import DontTrustBaseException

username = Schema().required().string()

try:
    print(username.validate(1234))
except DontTrustBaseException as e:
    # Exception thrown
    print(e.message)
Enter fullscreen mode Exit fullscreen mode
# By returning false instead of an exception
from donttrust import Schema

username = Schema().required().string()
print(username.validate_without_exception(1234))  # False
print(username.validate_without_exception("test"))  # test
Enter fullscreen mode Exit fullscreen mode

DontTrust class

The DontTrust class allows you to combine 1 or more schemas together.

from donttrust import DontTrust, Schema, ValidationError

try:
    trust = DontTrust(username=Schema().string().required().alphanum().min(4).max(32).strip().to_lower()
                      password=Schema().string().required().min(8))

    print(trust.validate(username="UseRNAME    ", password="pas5word1"))  # {"username": "username", "password": "pas5word1"}
    print(trust.validate({"username": "1NV@LID"}))  # Exception
except ValidationError as e:
    print(e.message)
Enter fullscreen mode Exit fullscreen mode

And that's it for this python library! For more information, visit the Docs, API Reference or the Github repository *(and drop a star while you're there ❀️)

If you have any suggestions for this project, create a Github issue or comment it down below. I'll try my best to implement it πŸ₯³

Top comments (0)