javascript sequelize.js自定义验证器,检查唯一的用户名/密码

ql3eal8s  于 2023-03-28  发布在  Java
关注(0)|答案(6)|浏览(154)

假设我已经定义了以下自定义验证器函数:

isUnique: function () { // This works as expected
  throw new Error({error:[{message:'Email address already in use!'}]});
}

然而,当我尝试查询DB时,我遇到了问题:

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.
    });
}

如何在自定义验证器中查询ORM并根据ORM的响应触发验证错误?

vatpfxk5

vatpfxk51#

您可以像这样验证电子邮件是否已经存在:

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

1aaf6o9v2#

下面是一个功能isUnique验证回调的简化示例(SequelizeJS v2.0.0)。我添加了注解来解释重要的部分:

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;
9njqaruj

9njqaruj3#

使用Sequelize 2.0,您需要捕获验证错误。
首先,使用自定义验证器定义用户模型:

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;

然后,在控制器中捕获任何验证错误:

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
            });
        });
flseospp

flseospp4#

即使没有找到用户,也会调用成功回调。你必须检查函数是否将用户作为参数传递:

isUnique: function (email) {
  var User = seqeulize.import('/path/to/user/model');

  User.find({where:{email: email}})
    .success(function (u) { // This gets called
      if(u){
        throw new Error({error:[{message:'Email address already in use!'}]});  // But this isn't triggering a validation error.
      }
    });
}
q43xntqr

q43xntqr5#

使用自定义验证器定义用户模型:

const { DataTypes } = require('sequelize');
const sequelize = require('../config/db');

const UserModel = sequelize.define('user', {
  id: {
    type: DataTypes.INTEGER(11).UNSIGNED,
    autoIncrement: true,
    primaryKey: true,
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      isUnique: (value, next) => {
        UserModel.findAll({
          where: { email: value },
          attributes: ['id'],
        })
          .then((user) => {
            if (user.length != 0)
              next(new Error('Email address already in use!'));
            next();
          })
          .catch((onError) => console.log(onError));
      },
    },
  },
  password: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  createdAt: {
    type: DataTypes.DATE,
    allowNull: false,
  },
  updatedAt: {
    type: DataTypes.DATE,
    allowNull: false,
  },
});

module.exports = UserModel;
ki0zmccv

ki0zmccv6#

对于那些已经在数据库中声明了约束,并且已经使用squelize-auto生成了表模型的人来说,替换以下内容就足够了:

us_mail: {
      type: DataTypes.STRING(150),
      allowNull: false,
      unique: 'us_mail_UNIQUE',
      validate:{
        notEmpty:{msg: 'Renseigner une adresse mail pour valider le compte'},
        notNull: {msg: 'Renseigner une adresse mail pour valider le compte'},
        isEmail:{msg: 'Renseigner une adresse mail valide !'},
      }
    },

与:

us_mail: {
      type: DataTypes.STRING(150),
      allowNull: false,
      unique: {name:'us_mail_UNIQUE',msg: 'Cette adresse mail est déjà utlisée'},
      validate:{
        notEmpty:{msg: 'Renseigner une adresse mail pour valider le compte'},
        notNull: {msg: 'Renseigner une adresse mail pour valider le compte'},
        isEmail:{msg: 'Renseigner une adresse mail valide !'},
      }
    },

相关问题