Permalink
Browse files

Merge pull request #26 from nodeca/feature-typecasting

Non-standard type-casting feature
  • Loading branch information...
2 parents 6c41ae2 + f6ae78a commit 77804b91faacaa3d4141f4f0ff25985e2ee8c0d3 @pksunkara pksunkara committed Oct 29, 2012
Showing with 34 additions and 1 deletion.
  1. +1 −0 README.md
  2. +6 −0 lib/revalidator.js
  3. +27 −1 test/validator-test.js
View
@@ -73,6 +73,7 @@ This will return with a value indicating if the `obj` conforms to the `schema`.
* __validateFormats__: Enforce format constraints (_default true_)
* __validateFormatsStrict__: When `validateFormats` is _true_ treat unrecognized formats as validation errors (_default false_)
* __validateFormatExtensions__: When `validateFormats` is _true_ also validate formats defined in `validate.formatExtensions` (_default true_)
+* __cast__: Enforce casting of some types (for integers/numbers are only supported) when it's possible, e.g. `"42" => 42`, but `"forty2" => "forty2"` for the `integer` type.
### Schema
For a property an `value` is that which is given as input for validation where as an `expected value` is the value of the below fields
View
@@ -237,6 +237,12 @@
}
}
+ if (options.cast) {
+ if (('integer' === schema.type || 'number' === schema.type) && value == +value) {
+ value = +value;
+ }
+ }
+
if (schema.format && options.validateFormats) {
format = schema.format;
View
@@ -340,6 +340,32 @@ vows.describe('revalidator', {
"and an error concerning the 'pattern' attribute": assertHasError('pattern')
},
}
- }
+ },
+ "with <cast> option": {
+ topic: {
+ properties: {
+ question: { type: "string" },
+ answer: { type: "integer" }
+ }
+ },
+ "when the property is castable": {
+ topic: function (schema) {
+ return revalidator.validate({ answer: "42" }, schema, { cast: true });
+ },
+ "return an object with `valid` set to true": assertValid
+ },
+ "when the property is uncastable": {
+ topic: function (schema) {
+ return revalidator.validate({ answer: "forty2" }, schema, { cast: true });
+ },
+ "return an object with `valid` set to false": assertInvalid
+ },
+ "casting should respect property type": {
+ topic: function (schema) {
+ return revalidator.validate({ question: "42" }, schema, { cast: true });
+ },
+ "return an object with `valid` set to true": assertValid
+ }
+ },
}
}).export(module);

0 comments on commit 77804b9

Please sign in to comment.