tv4
tv4 copied to clipboard
Possible to apply defaults on validation?
Hi!
Is it possible to have a mode where the validation can actively apply the default values of the schema to the properties of the validated object? This would be a great feature, since then I don't have handle the objects with gloves and test for property existence first.
Best, Simon
+1 Default values are very useful. I need it as well for a project of mine.
However, applying default values is not strictly a part of validation. Thus it gives the library 2 core functions; validation and applying default values. For that reason, a separate project would work fine too (this is done for JSV, see https://github.com/fhellwig/jsvutil).
Do you mean adding any default values there are, or adding default values for properties that are required?
In fact is implicitly changes the property to required, or at least it results in the property always having a value. Does require means that it should have that property before validation or after validation?
The JSON Schema standard has very little info about using "default": http://json-schema.org/latest/json-schema-validation.html#anchor101
Schema example:
{
"type": "object",
"properties": {
"title": {"type": "string"},
"published": {"type": "boolean", "default": true},
}
}
Input:
{"title": "test"}
should become:
{"title": "test", "published": true}
It doesn't make sense to add "required" in this schema, so we should probably ignore "required" when a default value is given.
Yes, exactly!
The use case would be to use JSON Schema for describing internal datastructures of a program. For example if a function expects a parameter to be an object, holding options.
Required is sort of ambigious in that case. But I guess it can safely be ignored. It doesn't much sense to require something but offer a default for it at the same time?
+1
Have you seen tv4-coerce
?
I started it a while ago, with the intention that it could provide "coercive validation" (an idea that would include e.g. inserting missing properties), but it didn't get much attention.