简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM