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

javascript, node.js, orm, sequelize.js

Solution

You can verify if the email already exists like that:

email: {
  type: Sequelize.STRING,
  allowNull: false,
  validate: {
    isEmail:true
  },
  unique: {
      args: true,
      msg: 'Email address already in use!'
  }
}

Problem

Imagine I have defined the following custom validator function: ``` isUnique: function () { // This works as expected throw new Error({error:[{message:'Email address already in use!'}]}); } ``` However, when I attempt to query the DB I run into problems: ``` isUnique: function (email) { // This doesn't work var User = seqeulize.import('/path/to/user/model'); User.find({where:{email: email}}) .success(function () { // This gets called throw new Error({error:[{message:'Email address already in use!'}]}); // But this isn't triggering a validation error. }); } ``` How can I query the ORM in a custom validator and trigger a validation error based on the response from the ORM?

Original source