A simple way to validate dictionary values by using functions.
Project description
A simple way to validate dictionary values by using functions.
Installation
pip3 install simple-validator
Usage
There are 2 main classes to create custom validation classes(Field, Validator).
from validator import Field, Validator
def is_valid_email(val: str):
""" A horrible way to check if a string is a valid email. """
passed = False
err_msg = "{} isn't a valid email.".format(val)
if '@' in val:
passed = True
return passed, err_msg
class UserValidator(Validator):
""" Validates a user dictionary. """
email = Field(data_type=str, validators=[is_valid_email])
Validation
The Validator provides the same api as Django forms for checking if all the fields are valid.
data = {
'email': 'Sean@parsons.com'
}
user = UserValidator(data)
if user.is_valid():
# Do things in here...
email = user.email # Optionally you can do user.data['email']
else:
print(user.errors)
Required Fields
To make a Field required, all that needs to be done is add required=True as a kwarg to the definition
If the field isn’t present it will be added to `Validator.errors under the key for the declared Field that is set to required.
class UserValidator(Validator):
""" Validates a user dictionary. """
email = Field(
data_type=str,
validators=[is_valid_email],
required=True
)
Errors
The Validator.errors attribute is a defaultdict(list).
When validators don’t pass, the declared field(Ex: ‘email’, ‘password’ etc..) errors gets populated with the return error string from the validator or required errors if the data is missing.
data = {
'email': 'sean'
}
user = UserValidator(data)
if user.is_valid():
# Do things in here...
else:
print(user.errors['email'])
# "sean isn't a valid email."
Validating Field Types
The Field class has a data_type parameter which should be used to validate a field value before passing it into validators.
This prevents from having try, except, else blocks inside of validator functions because your guaranteed it won’t be passed into validators until it’s the correct type.
If the field value is the wrong type, it will ony return an error like the one below
data = {
'email': 1
}
user = UserValidator(data)
if user.is_valid():
# Do things in here...
else:
print(user.errors['email'])
# "'1' is expected to be a 'String'"
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file simple-validator-1.0.3.tar.gz
.
File metadata
- Download URL: simple-validator-1.0.3.tar.gz
- Upload date:
- Size: 3.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | d51a4595bc9ca46b497f6149c1223e7613d5400275d6df68d65ff5d3bfbe9482 |
|
MD5 | e9736109714d094789f1a54e3d5856b9 |
|
BLAKE2b-256 | ea50d074164786c16428058e9fac08742920cca9059d9c80b304f3779a73ad08 |