javascript - sequelize.js custom validator, check for unique username / password -


imagine have defined following custom validator function:

isunique: function () { // works expected   throw new error({error:[{message:'email address in use!'}]}); } 

however, when attempt query db run problems:

isunique: function (email) { // doesn't work   var user = seqeulize.import('/path/to/user/model');    user.find({where:{email: email}})     .success(function () { // gets called       throw new error({error:[{message:'email address in use!'}]});  // isn't triggering validation error.     }); } 

how can query orm in custom validator , trigger validation error based on response orm?

here's simplified sample of functioning isunique validation callback (works of sequelizejs v2.0.0). added comments explain important bits:

var usermodel = sequelize.define('user', {      id: {         type: sequelize.integer(11).unsigned,         autoincrement: true,         primarykey: true     },     email: {         type: sequelize.string,         validate: {             isunique: function(value, next) {                  usermodel.find({                     where: {email: value},                     attributes: ['id']                 })                     .done(function(error, user) {                          if (error)                             // unexpected error occured find method.                             return next(error);                          if (user)                             // found user email address.                             // pass error next method.                             return next('email address in use!');                          // if got far, email address hasn't been used yet.                         // call next no arguments when validation successful.                         next();                      });              }         }     }  });  module.exports = usermodel; 

Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -