-
Notifications
You must be signed in to change notification settings - Fork 15
Validating Data
ZSchema can validate whether records confirm was a defined schema.
In a simple example:
r = Record({
"field":String(),
})
# executes successfully
r.validate({"field":"hello world"})
# raise DataValidationException
r.validate({"field":False})
Fields and types can specify one of several different validation poilcies (similar to how other field/type attributes are defined) by passing in one of the following values to validation_policy
:
-
error
: raises DataValidationException the first time a validation error occurs. This is the default for the root record. -
warn
: callslogging.warn
on every validation error. -
ignore
: does nothing on an a validation error -
inherit
: uses the field's parent's validation level. This is the default for all types except the root record.
By default all types use the validation policy inherit
, except for Recor
d,
which uses the default error
. This means that without any additional
confirmation, calling .validate
with a record that doesn't conform will lead
to a DataValidationException
exception.
You can also define more complex validation patterns. For example:
Child = SubRecordType({
"myField":String()
})
record = Record({
"willError":Child(validation_policy="error"),
"willWarn":Child(validation_policy="warn"),
"willIgnore":Child(validation_policy="ignore"),
# These two cases are identical, because by default types inherit
"willInherit":Child(),
"willInheritExplicitly":Child(validation_policy="inherit"),
})
When validating without any explicit policy specified, the record's policy will be used. For example:
# no errors
record.validate({"willIgnore":"garbage"})
# warnings provided
record.validate({"WillWarn":"garbage", "willIgnore":"garbage"})
# both will raise exceptions
record.validate({"willError":"garbage"})
record.validate({"willInherit":"garbage"})
However, it's possible to override as well, by specifiying a policy
when calling validate:
# DataValidationException will be raised:
record.validate({"willIgnore":"garbage"}, policy="error")