1

I have written a validation for the input that I receive but now the issue is that i have mentioned a type as date and whenever the date is empty I receive it as "". So is there any way that I can skip validation if input is ""?

My input:

{"suggested_relieving_date": ""}

My validation code:

class OffboardingSchema(Schema):

    suggested_relieving_date = fields.Date(format="%Y-%m-%d")`

The output:

{
    "success": false,
    "errors": {
        "suggested_relieving_date": [
            "Not a valid date."
        ]
    },
    "status": 400
}

I have changed the type to string for now but it is not a proper fix. I need to know if "" cases can be skipped or handled in anyway for date format.

Semo
  • 783
  • 2
  • 17
  • 38

1 Answers1

0

What do you think about switching empty strings to None in advance and accepting them?

This code converts all empty strings to None. But you can also differentiate based on the field name if you use a simple if condition.

from marshmallow import pre_load

class OffboardingSchema(Schema):
    suggested_relieving_date = fields.Date(
        required=False, 
        allow_none=True, 
        format='%Y-%m-%d'
    )

    @pre_load
    def string_to_none(self, data, many, **kwargs):
        for k, v in data.items():
            data[k] = v or None
        return data
Detlef
  • 6,137
  • 2
  • 6
  • 24