Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 961
Matt Richards Avatar asked May 03 '13 10:05

Matt Richards


1 Answers

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!'
  }
}
like image 78
alvaropaco Avatar answered Nov 03 '22 22:11

alvaropaco