Skip to content

Custom Validator per Model

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:

var User = model("User").attr('name', {
  validations: {
    presence: true,
    //name the validator as you wish, it may contain any meta data the custom validator may need
    uniqueUserName: {
      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: name
  console.log(options);
    //prints: message: 'Name already exist.'
  });
  if (model[property]() === 'foo') {
    model.addError(property, options.message);
  }
});


var u1 = User.create();
u1.name('foo');
u1.validate().then(function() {
  console.log(u1.isValid);
  //prints false
  console.log(u1.errors);
  //prints name: ['Name already exist.']
});
Clone this wiki locally