0

I'm looking to validate the datetime type with custom validator, rather than the built in one.

The code looks like this:

        schema_text = """
            run_date:
                type: datetime
                required: true
            """
        s.schema = yaml.load(schema_text)

        s.validate(yaml.load("run_date: 2017-01-01T00:00+00:00:00"))

I could do this using checks_with: my_custom_validator, which would be ok but I'm hoping to open these schemas up to the public, so asking them all to contribute to them would be a bother. I think this could also be done using a normalizer but, again, I'd prefer not to munge with the input.

Any suggestions here? The dateutil parser is exactly what I want to use.

aronchick
  • 6,786
  • 9
  • 48
  • 75
  • Type checking operates on the Python type dimension. When you have a structured string that may be *mentally* something else, but you need to parse it into the type that you want to validate. In case you want to check the structure of a string, use the regex rule. – funky-future Apr 05 '20 at 11:11
  • What I'm trying to do is take the type declaration, and, if it is something I recognize (e.g. datetime), I process it with a custom validator that i want, instead of using the standard Python type definition. Is that possible? Or should I just define a new type? – aronchick Apr 08 '20 at 01:59
  • What you got from the parsed yaml is a string, isn't it? – funky-future Apr 08 '20 at 12:39
  • yep - it comes from a string – aronchick Apr 17 '20 at 15:37

1 Answers1

2

As your input data is a string which represents a datetime in ISO 8601 format, you can use two approaches without any customization.

Either (try to) convert the string to a datetime.datetime object:

from datetime import datetime

schema = {
    "run_date": {"coerce": datetime.fromisoformat}
}

This would need to be validated with normalization and either cause an error or cast the run_date field's value into a datetime.datetime object.

If you want to stick with a string as data type, use the regex rule:

schema = {
    "run_date": {"type": "string", "regex": r"\d{4}-\d\d-\d\d-etc.pp."}
}
funky-future
  • 3,716
  • 1
  • 30
  • 43
  • Oh, I appreciate this - unfortunately, I want to be able to accept schema from the public, and was hoping for something simpler than having them either understand what a coerce is or having to do a regex. I think both these work, though - so I'll do the checkmark. – aronchick Apr 21 '20 at 17:22