2

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.

user3142695
  • 15,844
  • 47
  • 176
  • 332

1 Answers1

4

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

mparkitny
  • 1,165
  • 1
  • 9
  • 16
  • For me it is not working. Please have a look at https://stackoverflow.com/questions/44943512/simpleschema-conditionally-required-field-is-not-working – user3142695 Jul 06 '17 at 08:24
  • @user3142695 you are right. I found the error and will update answer in minutes. – mparkitny Jul 06 '17 at 09:04