user3142695
user3142695

Reputation: 17342

SimpleSchema: Depending values instead of optional values

This is how my SimpleSchema validation looks like:

validate: new SimpleSchema({
    type: { type: String, allowedValues: ['start', 'stop'] },
    _id : { type: SimpleSchema.RegEx.Id, optional: true },
    item: { type: String, optional: true }
}).validator()

But it is not exactly what I am needing:

If type is start, there must be a item value and if type is stop there must be an _id value.

Upvotes: 2

Views: 936

Answers (1)

mparkitny
mparkitny

Reputation: 1195

You can achieve this by changing your code like below

validate: new SimpleSchema({
  type: { type: String, allowedValues: ['start', 'stop'] },
  _id : { 
    type: SimpleSchema.RegEx.Id, 
    optional: true,
    custom: function () {
      if (this.field('type').value == 'stop') {
        return SimpleSchema.ErrorTypes.REQUIRED
      }
    } 
  },
  item: { 
    type: String, 
    optional: true,
    custom: function () {
      if (this.field('type').value == 'start') {
        if(!this.isSet || this.value === null || this.value === "") {
          return SimpleSchema.ErrorTypes.REQUIRED
        }
      }
    }
  }
}).validator()

If you use atmosphere package of SimpleSchema you can replace return SimpleSchema.ErrorTypes.REQUIRED with return 'required'. I tested above code only using NPM package and both versions worked fine.

This is a very basic implementation of this functionality. SimpleSchema even allows to conditionally require field depending on the performed operation(insert, update).

You can read more about it in the docs

Upvotes: 4

Related Questions