Validators - circuitsacul/apgorm GitHub Wiki

Basic Validator

apgorm also supports python-side validation in addition to constraints. They can be used like this:

def check_gt_zero(value: int) -> bool:
    if value <= 0:
        return False
    return True


my_int_field = Int().field()
my_int_field.add_validator(check_gt_zero)

Now, if you pass a value that is less than 1, you will get an InvalidFieldValue exception.

Note: Validators are ignored by methods such as .fetch(). This way you can add a validator to a field even if the database already contains values that would be considered invalid without breaking things.

Descriptive Exceptions

If you want a more descriptive exception, you can raise InvalidFieldValue inside of the validator instead of just returning False. For example:

def check_gt_zero(value: int) -> bool:
    if value > 0:
        return True
    raise apgorm.exceptions.InvalidFieldValue(f"{value} must be greater than 0")