Custom Validators¶
You can add a custom validator by creating a class and inheriting from
Validator (from func_validator import Validator) base class. Implement
the __call__ method to accept arguments in the order arg_value and
arg_name. Raise a ValidationError
(from func_validator import ValidationError) if validation fails.
Example Custom Validator¶
In [10]:
Copied!
# Config to have a single line output of Exception error message
import sys; sys.tracebacklimit = 0;
%xmode plain
# Config to have a single line output of Exception error message
import sys; sys.tracebacklimit = 0;
%xmode plain
Exception reporting mode: Plain
Imports¶
In [11]:
Copied!
from typing import Annotated
from func_validator import validate_params, Validator, ValidationError
from typing import Annotated
from func_validator import validate_params, Validator, ValidationError
Code Example¶
In [12]:
Copied!
class MustBeEven(Validator):
def __call__(self, arg_value, arg_name: str):
if arg_value % 2 != 0:
raise ValidationError(f"{arg_name}:{arg_value} must be even")
class MustBeEven(Validator):
def __call__(self, arg_value, arg_name: str):
if arg_value % 2 != 0:
raise ValidationError(f"{arg_name}:{arg_value} must be even")
In [13]:
Copied!
@validate_params
def fn(param_1: Annotated[int, MustBeEven()]):
return param_1 * param_1
@validate_params
def fn(param_1: Annotated[int, MustBeEven()]):
return param_1 * param_1
In [14]:
Copied!
fn(param_1=10)
fn(param_1=10)
Out[14]:
100
In [15]:
Copied!
fn(param_1=11)
fn(param_1=11)
ValidationError: param_1:11 must be even