tv4 icon indicating copy to clipboard operation
tv4 copied to clipboard

Possible to apply defaults on validation?

Open Fannon opened this issue 9 years ago • 6 comments

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

Fannon avatar Feb 18 '15 09:02 Fannon

+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).

mauritsl avatar Mar 16 '15 10:03 mauritsl

Do you mean adding any default values there are, or adding default values for properties that are required?

geraintluff avatar Mar 24 '15 16:03 geraintluff

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.

mauritsl avatar Mar 24 '15 20:03 mauritsl

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?

Fannon avatar Mar 27 '15 06:03 Fannon

+1

adius avatar Jul 18 '15 09:07 adius

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.

geraintluff avatar Jul 20 '15 17:07 geraintluff