Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Declare field validator with decorator #585

Open
JoMingyu opened this issue Feb 11, 2019 · 1 comment
Open

Declare field validator with decorator #585

JoMingyu opened this issue Feb 11, 2019 · 1 comment

Comments

@JoMingyu
Copy link

When I define a model like this,

from schematics import Model
from schematics.types import *

class DummySchema(Model):
    from_ = DateType(
        serialized_name='from',
        required=True
    )
    to = DateType(
        serialized_name='to',
        required=True
    )

The way to specify additional validators for each field is as follows.

from schematics import Model
from schematics.exceptions import ValidationError
from schematics.types import *

def validate_year_of_to_is_2019(value):
    if value.year != 2019:
        raise ValidationError('year of to should be 2019.')

class DummySchema(Model):
    from_ = DateType(
        serialized_name='from',
        required=True
    )
    to = DateType(
        serialized_name='to',
        required=True,
        validators=[validate_year_of_to_is_2019]
    )

It would be nice if the field validator could be defined as a decorator.

from schematics import Model
from schematics.exceptions import ValidationError
from schematics.types import *

class DummySchema(Model):
    from_ = DateType(
        serialized_name='from',
        required=True
    )
    to = DateType(
        serialized_name='to',
        required=True
    )
    
    @to.validator
    def validate_year_of_to_is_2019(self, value):
        if value.year != 2019:
            raise ValidationError('year of to should be 2019.')
@ljluestc
Copy link

from schematics import Model
from schematics.exceptions import ValidationError
from schematics.types import *
from functools import wraps

def validate_year_of_to_is_2019(func):
@wraps(func)
def wrapper(self, value):
if value.year != 2019:
raise ValidationError('year of to should be 2019.')
return func(self, value)
return wrapper

class CustomDateType(DateType):
def init(self, *args, **kwargs):
super().init(*args, **kwargs)

def validator(self, func):
    return validate_year_of_to_is_2019(func)

class DummySchema(Model):
from_ = DateType(
serialized_name='from',
required=True
)
to = CustomDateType(
serialized_name='to',
required=True
)

@validate_year_of_to_is_2019
def validate_to_year(self, value):
    pass

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants