3

I need to validate JSON files in following way:

const setupSchema = fs.readFileSync(schemaDir +'/setup.json');

and compiling:

const setupValidator = ajv.compile(setupSchema);

My issue is that line:

console.log( setupValidator('') );

Always returns true even as validator's parameter is empty string like above. I suppose that the way of loading is bad but... need ask smarter people than me.

Tomasz Waszczyk
  • 2,680
  • 5
  • 35
  • 73

2 Answers2

3

From the quick start guide: (http://json-schema.org/)

The JSON document being validated or described we call the instance, and the document containing the description is called the schema.

The most basic schema is a blank JSON object, which constrains nothing, allows anything, and describes nothing:

{}

You can apply constraints on an instance by adding validation keywords to the schema. For example, the “type” keyword can be used to restrict an instance to an object, array, string, number, boolean, or null:

{ "type": "string" }

This means that if your schema is either an empty object or does not use the JSON Schema vocabulary, Ajv's compile function will always generate a validation function that always passes:

var Ajv = require('ajv');
var ajv = new Ajv({allErrors: true});

var schema = {
    foo: 'bar',
    bar: 'baz',
    baz: 'baz'
};

var validate = ajv.compile(schema);

validate({answer: 42}); //=> true
validate('42'); //=> true
validate(42); //=> true

Perhaps your setup.json is either incorrectly loaded or isn't a schema as per the JSON Schema specification.

customcommander
  • 17,580
  • 5
  • 58
  • 84
1
// You should specify encoding while reading the file otherwise it will return raw buffer
const setupSchema = fs.readFileSync(schemaDir +'/setup.json', "utf-8");
// setupSchema is a JSON string, so you need to parse it before passing it to compile as compile function accepts an object
const setupValidator = ajv.compile(JSON.parse(setupSchema));
console.log( setupValidator('') ) // Now, this will return false;

Instead of doing above, you can just simply require the json file using require.

const setupSchema = require(schemaDir +'/setup.json');
const setupValidator = ajv.compile(setupSchema);
console.log( setupValidator('') );