question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Hello everyone! I would like to add a new validator to combine multiple validators into one. Simple example:

def calculate_age(birthday: date) -> int:
    today = date.today()
    offset = (today.month, today.day) < (birthday.month, birthday.day)
    return today.year - birthday.year - offset

def validate_not_future_date(value: date) -> None:
    if value > date.today():
        raise ValidationError("Not future date.")

def validate_14_years_old(value: date) -> None:
    if calculate_age(value) < 14:
        raise ValidationError("Must be 14 years old.")

class PassportSchema(Schema):
    issued_at = fields.Date(
        "%Y-%m-%d",
        validate=[
            validate_not_future_date,
            validate_14_years_old,
        ],
    )

    @post_load
    def make_passport(self, data: dict, **kwargs) -> Passport:
        return Passport(**data)

@attr.s(auto_attribs=True, slots=True, frozen=True)
class Passport:
    issued_at: date

    def __attrs_post_init__(self) -> None:
        validate_not_future_date(self.issued_at)
        validate_14_years_old(self.issued_at)

In this example, I am forced to pass validators as a list in the issued_at field (in PassportSchema) and call two functions to validate a single value in Passport entity. I would like to combine the two functions into one and turn them into a single validator:

T = TypeVar("T")

Validator = Callable[[T], T]

@attr.s(auto_attribs=True, slots=True, frozen=True)
class _AndValidator:
    validators: Sequence[Validator]

    def __call__(self, value: T) -> T:
        for validator in self.validators:
            validator(value)
        return value

def and_validator(*validators) -> _AndValidator:
    return _AndValidator(validators)

validate_passport_issued_at = and_validator(
    validate_14_years_old,
    validate_not_future_date,
)

Then the example above will look much more concise:

class PassportSchema(Schema):
    issued_at = fields.Date("%Y-%m-%d", validate=validate_passport_issued_at)

    @post_load
    def make_passport(self, data: dict, **kwargs) -> Passport:
        return Passport(**data)

@attr.s(auto_attribs=True, slots=True, frozen=True)
class Passport:
    issued_at: date

    def __attrs_post_init__(self) -> None:
        validate_passport_issued_at(self.issued_at)

I would like to add such functionality to the marshmallow.validate package.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:11 (7 by maintainers)

github_iconTop GitHub Comments

2reactions
deckar01commented, Mar 23, 2021

@rugleb Please review our code of conduct. Your behavior is inappropriate. Please be respectful to other users.

https://marshmallow.readthedocs.io/en/dev/code_of_conduct.html

1reaction
sloriacommented, Mar 30, 2021

Actually, I took a stab at this in #1777.

Read more comments on GitHub >

github_iconTop Results From Across the Web

JSON Formatter & Validator
The JSON Formatter & Validator beautifies and debugs JSON data with advanced formatting and validation algorithms.
Read more >
The W3C Markup Validation Service
This validator checks the markup validity of Web documents in HTML, XHTML, SMIL, MathML, etc. If you wish to validate specific content such...
Read more >
JSON Online Validator and Formatter - JSON Lint
JSONLint is the free online validator and reformatter tool for JSON, a lightweight data-interchange format.
Read more >
Verification and validation - Wikipedia
Verification and validation (also abbreviated as V&V) are independent procedures that are used together for checking that a product, service, ...
Read more >
Free online XML formatter and validator - elmah.io
The most advanced XML formatter and validator. Free pretty-print of any XML file with a range of options to control spaces, tabs, and...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found