lukejagodzinski / meteor-astronomy-validators

https://atmospherejs.com/jagi/astronomy-validators
MIT License
11 stars 13 forks source link

validation doesn't work for array elements #13

Closed laurentpayot closed 8 years ago

laurentpayot commented 8 years ago

I'm trying to set validators for an array of tags but it doesn't seem to work. Am I doing it the right way?

(I'm quickly pasting my CoffeeScript code, hope you don't mind...)

V = Validators
@Foos = new Mongo.Collection('foos')
@Foo = Astro.Class(
    name: 'Foo'
    collection: Foos
    fields:
        'tags':
            type: 'array'
            default: []
            index: true
            validators: [V.required(), V.array(), V.maxLength(100)]
        'tags.$':
            type: 'object'
            default: {}
            validators: [V.object()]
        'tags.$.tag':
            type: 'string'
            validators: [V.required(), V.string(), V.minLength(2), V.maxLength(20)]
)

When I validate it in Meteor shell I get the following:

> f = new Foo({tags:[1]})
{ _values: { tags: [ 1 ], _id: null },
  _original: { _id: null },
  _isNew: true,
  _errors: 
   { _size: 0,
     _values: {},
     _sizeDeps: { _dependentsById: {} },
     _allDeps: { _dependentsById: {} },
     _keysDeps: { _dependentsById: {} },
     _valuesDeps: { _dependentsById: {} },
     _keyDeps: {},
     _hasDeps: {} } }
> f.validate()
true
> f = new Foo({tags:[""]})
{ _values: { tags: [ '' ], _id: null },
  _original: { _id: null },
  _isNew: true,
  _errors: 
   { _size: 0,
     _values: {},
     _sizeDeps: { _dependentsById: {} },
     _allDeps: { _dependentsById: {} },
     _keysDeps: { _dependentsById: {} },
     _valuesDeps: { _dependentsById: {} },
     _keyDeps: {},
     _hasDeps: {} } }
> f.validate()
true
>
lukejagodzinski commented 8 years ago

Hi, you have an error in you code. You've defined the tags.$.tag validator as the field instead validator. Nested validators have to be defined under the validators property in the schema.

In fact the way you define nested fields and validators will change in the next release which is going to be published soon.

laurentpayot commented 8 years ago

Thanks for your quick answer. I'm closing the issue, waiting for the next release then... :hourglass:

lukejagodzinski commented 8 years ago

And to make it clear for all I will post the correct code:

var V = Validators;

Foos = new Mongo.Collection('foos');
Foo = Astro.Class({
  name: 'Foo',
  collection: Foos,
  fields: {
    'tags': {
      type: 'array',
      default: [],
      index: true,
      validators: [V.required(), V.array(), V.maxLength(100)]
    },
  validators: {
    'tags.$': [V.object()],
    'tags.$.tag': [V.required(), V.string(), V.minLength(2), V.maxLength(20)]
  }
});
laurentpayot commented 8 years ago

:+1: