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

后端 未结 4 833
野趣味
野趣味 2021-02-02 03:47

Imagine I have defined the following custom validator function:

isUnique: function () { // This works as expected
  throw new Error({error:[{message:\'Email addr         


        
4条回答
  •  忘掉有多难
    2021-02-02 04:13

    Here's a simplified sample of a functioning isUnique validation callback (works as of SequelizeJS v2.0.0). I added comments to explain the 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)
                                // Some unexpected error occured with the find method.
                                return next(error);
    
                            if (user)
                                // We found a user with this email address.
                                // Pass the error to the next method.
                                return next('Email address already in use!');
    
                            // If we got this far, the email address hasn't been used yet.
                            // Call next with no arguments when validation is successful.
                            next();
    
                        });
    
                }
            }
        }
    
    });
    
    module.exports = UserModel;
    

提交回复
热议问题