tdegrunt/jsonschema — pull request #68 by hugowetterberg (2014-02-10 20:20:14+00:00)
Title: Add a preValidateProperty hook that allows features like type coercion t...

...o be implemented by users of the module.

I'm currently implementing request & response validation using jsonschema for hapi. A problem I hit was the strict type-checking of jsonschema. I realise that this is a good thing in itself, but to be able to use schemas for query strings and path segments I needed some type coercion. As this isn't something that should be done in the jsonschema module I propose that we add the possibility to hook in before property validation using a function on the options object.

In the case of my module I would then simply provide a preValidateProperty function like this:

```javascript
function (instance, property, schema, options, ctx) {
var value = instance[property];

// Skip nulls and undefineds
if (value === null || typeof value == 'undefined') {
return;
}

// If the schema declares a type and the property fails type validation.
if (schema.type && this.attributes.type.call(this, instance, schema, options, ctx.makeChild(schema, property))) {
var types = (schema.type instanceof Array) ? schema.type : [schema.type];
var coerced = undefined;

// Go through the declared types until we find something that we can
// coerce the value into.
for (var i = 0; typeof coerced == 'undefined' && i < types.length; i++) {
// If we support coercion to this type
if (lib.coercions[types[i]]) {
// ...attempt it.
coerced = lib.coercions[types[i]](value);
}
}
// If we got a successful coercion we modify the property of the instance.
if (typeof coerced != 'undefined') {
instance[property] = coerced;
}
}
}.bind(validator)
```

...that takes care of all the ugliness.