Bug 1467593 - Support non-strict arrays in the JsonSchemaValidator. r=mythmon
An array specified with strict=false will not fail validation if there are invalid values. It simply will ignore those values and not include them in the output.
If strict is missing, it defaults to true.
MozReview-Commit-ID: 7hAs0IsnL9v
--- a/toolkit/components/utils/JsonSchemaValidator.jsm
+++ b/toolkit/components/utils/JsonSchemaValidator.jsm
@@ -75,22 +75,31 @@ function validateAndParseParamRecursive(
return validateAndParseSimpleParam(param, properties.type);
case "array":
if (!Array.isArray(param)) {
log.error("Array expected but not received");
return [false, null];
}
+ // strict defaults to true if not present
+ let strict = true;
+ if ("strict" in properties) {
+ strict = properties.strict;
+ }
+
let parsedArray = [];
for (let item of param) {
log.debug(`in array, checking @${item}@ for type ${properties.items.type}`);
let [valid, parsedValue] = validateAndParseParamRecursive(item, properties.items);
if (!valid) {
- return [false, null];
+ if (strict) {
+ return [false, null];
+ }
+ continue;
}
parsedArray.push(parsedValue);
}
return [true, parsedArray];
case "object": {
--- a/toolkit/components/utils/test/browser/browser_JsonSchemaValidator.js
+++ b/toolkit/components/utils/test/browser/browser_JsonSchemaValidator.js
@@ -169,16 +169,43 @@ add_task(async function test_array_value
is(parsed.length, 0, "array is correct");
// Invalid values:
ok(!JsonSchemaValidator.validateAndParseParameters([1, true, 3], schema)[0], "Mixed types");
ok(!JsonSchemaValidator.validateAndParseParameters(2, schema)[0], "Type is correct but not in an array");
ok(!JsonSchemaValidator.validateAndParseParameters({}, schema)[0], "Object is not an array");
});
+add_task(async function test_non_strict_arrays() {
+ // Non-srict arrays ignores invalid values (don't include
+ // them in the parsed output), instead of failing the validation.
+ // Note: invalid values might still report errors to the console.
+ let schema = {
+ type: "array",
+ strict: false,
+ items: {
+ type: "string"
+ }
+ };
+
+ let valid, parsed;
+ [valid, parsed] = JsonSchemaValidator.validateAndParseParameters(
+ ["valid1", "valid2", false, 3, "valid3"], schema);
+ ok(valid, "Array is valid");
+ ok(Array.isArray(parsed, "parsed is an array"));
+ is(parsed.length, 3, "Only valid values were included in the parsed array");
+ Assert.deepEqual(parsed, ["valid1", "valid2", "valid3"], "Results were expected");
+
+ // Checks that strict defaults to true;
+ delete schema.strict;
+ [valid, parsed] = JsonSchemaValidator.validateAndParseParameters(
+ ["valid1", "valid2", false, 3, "valid3"], schema);
+ ok(!valid, "Same verification was invalid without strict=false");
+});
+
add_task(async function test_object_values() {
let schema = {
type: "object",
properties: {
url: {
type: "URL"
},
title: {