You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Asaf Shakarchi edited this page Aug 7, 2013
·
2 revisions
Here's a situation:
You have some Model, for the sake of the example, a User model, and lets say that you want to create a non-existing validator only for the User model which determines uniqueness,
So this validation should perform some DB query to ensure a user doesn't already exist as a part of the model instance validation, this is very simple to achieve with nodejs-model:
First, create a model:
varUser=model("User").attr('name',{validations: {presence: true,//name the validator as you wish, it may contain any meta data the custom validator may needuniqueUserName: {message: 'User name already exist.'}}});//Now hook a custom validator into the User model//model: The model instance being validated//property: The property name being validated, in this case it is the name property//This method is executed when modelInstance.validate() is invoked (see below!)User.validator('uniqueUserName',function(model,property,options){console.log(model.name());//prints: foo console.log(property);//prints: nameconsole.log(options);//prints: message: 'Name already exist.'});if(model[property]()==='foo'){model.addError(property,options.message);}});varu1=User.create();u1.name('foo');u1.validate().then(function(){console.log(u1.isValid);//prints falseconsole.log(u1.errors);//prints name: ['Name already exist.']});