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
Schemas
Schemas are what define a field in your form. There are 6 types of schemas currently:
- string
- number (includes
int
,float
andcomplex
) - date
- boolean
- any type
To initialise a schema:
from donttrust import Schema
username_field = Schema("username")
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
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)
# 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
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)
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)