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.
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.