Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validating top-level arrays #62

Open
JasonTypesCodes opened this issue Jul 25, 2018 · 4 comments
Open

Validating top-level arrays #62

JasonTypesCodes opened this issue Jul 25, 2018 · 4 comments

Comments

@JasonTypesCodes
Copy link

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?

@eivindfjeldstad
Copy link
Owner

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.

@JasonTypesCodes
Copy link
Author

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.

@gijo-varghese
Copy link

+1

@ibbignerd
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants