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

后端 未结 4 723
野趣味
野趣味 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:09

    With Sequelize 2.0, you need to catch Validation Errors.

    First, define the User Model with a custom validator:

    var User = sequelize.define('User',
        {
            email: {
                type: Sequelize.STRING,
                allowNull: false,
                unique: true,
                validate: {
                    isUnique: function (value, next) {
                        var self = this;
                        User.find({where: {email: value}})
                            .then(function (user) {
                                // reject if a different user wants to use the same email
                                if (user && self.id !== user.id) {
                                    return next('Email already in use!');
                                }
                                return next();
                            })
                            .catch(function (err) {
                                return next(err);
                            });
                    }
                }
            },
            other_field: Sequelize.STRING
        });
    
    module.exports = User;
    

    Then, in the controller, catch any Validation Errors:

    var Sequelize = require('sequelize'),
        _ = require('lodash'),
        User = require('./path/to/User.model');
    
    exports.create = function (req, res) {
        var allowedKeys = ['email', 'other_field'];
        var attributes = _.pick(req.body, allowedKeys);
        User.create(attributes)
            .then(function (user) {
                res.json(user);
            })
            .catch(Sequelize.ValidationError, function (err) {
                // respond with validation errors
                return res.status(422).send(err.errors);
            })
            .catch(function (err) {
                // every other error
                return res.status(400).send({
                    message: err.message
                });
            });
    

提交回复
热议问题