Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJV's validator returns always true value

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.

like image 790
Tomasz Waszczyk Avatar asked Oct 22 '25 01:10

Tomasz Waszczyk


1 Answers

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.

like image 178
customcommander Avatar answered Oct 24 '25 15:10

customcommander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!