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

Feature request: Exact Array #1

Closed
esamattis opened this issue Jul 21, 2012 · 2 comments
Closed

Feature request: Exact Array #1

esamattis opened this issue Jul 21, 2012 · 2 comments

Comments

@esamattis
Copy link

First of all thanks for this awesome library!

This can be also a documentation issue because I could not figure out how to do it. I'd like to have a way to validate that I have some exact array in my object.

For example

{
  "ducks": [
    {"age": 1},
    {"age": 7}
  ]
}

Closest thing I managed to create is this:

var YoungDuck = schema({ age: 1 });
var OldDuck = schema({ age: 7 });

var Animals = schema({
  ducks: schema({
    0: YoungDuck,
    1: OldDuck
  }),
})

but this of course validates this too

{
  "ducks": [
    {"age": 1},
    {"age": 7},
    {"age": "bad!"}
  ]
}

Could it be possible to have something like this?

var Animals = schema({
  ducks: Array.exact([
    YoungDuck,
    OldDuck
  ]),
})
@molnarg
Copy link
Owner

molnarg commented Jul 23, 2012

There should be a simpler way to do it, but for now, try this:

var YoungDuck = schema({ age: 1 });
var OldDuck = schema({ age: 7 });

var Animals = schema({
  ducks: schema({
    0: YoungDuck,
    1: OldDuck,
    '*': null, // or length : 2
    constructor: Function.reference(Array)
  }),
})

The only modification I made to your example is that I added the '*': null, and the constructor: Function.reference(Array) attribute. If you don't need it to be a real array, just remove the constraint for the constructor.

Also consider using the deep equality pattern if applicable in your case ([[ { age: 1 }, { age: 7 } ]])

I think that the array handling of js-schema is still very immature, and it would be nice to solve its issues in a more general way. But for now, your Array.exact is the best quick solution I can think of. I will close this ticket for now, but feel free to send a pull request with an Array.exact implementation. Array handling will definitely be improved in the future.

@molnarg molnarg closed this as completed Jul 23, 2012
@molnarg
Copy link
Owner

molnarg commented Jul 23, 2012

By the way, you don't need to nest schema calls inside schema calls, so the simplified solution would be this:

var YoungDuck = schema({ age: 1 });
var OldDuck = schema({ age: 7 });

var Animals = schema({
  ducks: {
    0: YoungDuck,
    1: OldDuck,
    '*': null, // or length : 2
    constructor: Function.reference(Array)
  }
})

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

2 participants