0

I want to re-use some validation rules (login / register). However, if I assign validations to the User schema, jugglingdb also adds these validations to the BaseUser (which is not what I want and I don't know how this happens)

// Provide user properties to re-use for login validation
var common_properties = {
  email    : String,
  password : String
};

var common_validations = [ 
  ['email',    {validation: 'presence'}],
  ['email',    {validation: 'format', with: /@.*?\./}],
  ['password', {validation: 'presence'}],
  ['password', {validation: 'length', min: 6}] 
];

var BaseUser = schema.define('BaseUser', common_properties);
    BaseUser._validations = common_validations;


var User = schema.define('User', _.extend(common_properties, {
  name     : String,
  salt     : String,
  created  : { type: Date, default: Date.now }
}));

User._validations = common_validations;

User.validatesPresenceOf('name');
User.validatesUniquenessOf('email');


console.log(BaseUser._validations)

// [ [ 'email', { validation: 'presence' } ],
//  [ 'email', { validation: 'format', with: /@.*?\./ } ],
//  [ 'password', { validation: 'presence' } ],
//  [ 'password', { validation: 'length', min: 6 } ],
//  [ 'name', { validation: 'presence' }, undefined ],            Should not be here??
//  [ 'email', { validation: 'uniqueness' }, { async: true } ] ]  Should not be here??

Does anyone know how javascript / jugglingdb does this? I just want to assign the common_validations to BaseUser, nothing else.

Tessmore
  • 1,054
  • 1
  • 9
  • 23

1 Answers1

0

I haven't traced through it, but I'm guessing the problem is that you're assigning the same validations array (common_validations) to both the BaseUser and User constructors. Since both BaseUser and User have a _validations property that point to the same array instance, adding a new validation adds a new entry to that array, and therefore it shows up on both types.

Try assigning _validations to a copy of the common_validations array instead of pointing to a shared instance.

Kevin Dente
  • 25,430
  • 7
  • 43
  • 47
  • Hmm, yes I hope your answer helps people. As far as I know, there is no real way to clone/copy objects in javascript? So assigning it to a copy of `common_validations` would mean I have to recreate the object . This pretty much makes my 'extension' useless. (But thanks for the answer!) – Tessmore Sep 04 '13 at 22:31
  • You don't need to deep clone all the objects - just make a shallow copy of the array. Eg. BaseUser._validations = common_validations.slice(0); – Kevin Dente Sep 05 '13 at 22:38