Validating top-level arrays
Opened this issue · 4 comments
I have been trying to write a schema that validates the properties of an array without much luck. Here is what I am trying:
const Schema = require('validate');
const schema1 = new Schema([
{
name: {
type: String,
required: true
},
age: {
type: Number,
required: true
}
}
]);
const schema2 = new Schema({
type: Array,
each: {
name: {
type: String,
required: true
},
age: {
type: Number,
required: true
}
}
});
// Should be valid
const input1 = [
{
name: 'joe',
age: 1
},
{
name: 'jill',
age: 2
}
];
// Should also be valid
const input2 = [];
// Should not be valid
const input3 = [
{
name: 'joe',
age: 3
},
{
something: 'different'
}
];
// These all fail
console.log(schema1.validate(input1));
console.log(schema1.validate(input2));
console.log(schema1.validate(input3));
console.log(schema2.validate(input1));
console.log(schema2.validate(input2));
console.log(schema2.validate(input3));
Is there a trick that I'm missing?
It's not really designed to work with top-level arrays, but a PR is welcome. I don't think there's a lot that needs to be done for it to work.
Yeah I dug around a bit and found that the reliance on having a "path" for each prop is what stops this from working as I hoped it would. I believe I would have encountered the same problem if I would try to make a schema that represents just a number or just a boolean or anything really that isn't an object at the top level.
+1
If you wanted to define a fixed width array, you could do it like this:
const myArraySchema = new Schema([
{
type: String,
required: true
}, {
type: Number,
required: true
}, {
type: undefined,
}
]);
const myValidArray = ['hi', 1];
console.log('myValidArray', myArraySchema.validate(myValidArray));
Of course it would be best to just add the ability to create a schema with just an array or just a type.