maritz / nohm

node.js object relations mapper (orm) for redis
http://maritz.github.io/nohm/
MIT License
500 stars 64 forks source link

Validating properties against other properties #94

Closed johngeorgewright closed 8 years ago

johngeorgewright commented 9 years ago

We have a situation where one of the properties needs to be validated against another property. This (simplified) example can give an idea as to what I'm trying to achieve:

// my-model.js
nohm.model('MyModel', {
  properties: {
    channel: {
      type: 'string',
      validators: [
        'validChannel'
      ]
    },
    subchannel: {
      type: 'string',
      validators: [
        'validSubchannel'
      ]
    }
  }
});
// validators.js
var channels = ['channel1', 'channel2'];
var subchannels = {
  channel1: ['subchannel1', 'subchannel2'],
  channel2: ['subchannel2', 'subchannel3']
};

exports.validChannel = function (value, options, callback) {
  callback(channels.indexOf(value) > -1);
};

exports.validSubchannel = function (value, options, callback) {
  var channel = this.p('channel'); // Uncaught TypeError: Object #<Object> has no method 'p'
  var validSubchannels = subchannels[channel];
  callback(validSubchannels.indexOf(value) > -1);
};

Is there any way I can access the current instance from within a validator?

maritz commented 9 years ago

Not right now.

https://github.com/maritz/nohm/blob/master/lib/validation.js#L177

Changing that line to something that uses apply should fix it.

If you wanna try that, a pull request with unit tests would be greatly appreciated. Otherwise it will take me at least a couple of days until I get around to doing it.

morgandonze commented 9 years ago

I could use this feature too. I think I'll take a shot at it this weekend.

johngeorgewright commented 9 years ago

I've been using this branch: https://github.com/maritz/nohm/pull/95 Although the tests don't seem to passing on Travis, they work for me.

maritz commented 8 years ago

This was fixed in February, forgot to close it.