2017-06-15 122 views
1

这里是我的检查电子邮件ID模型验证存在与否sequelize.js ORM:唯一的电子邮件验证为MySQL不工作

email:{ 
      type:Sequelize.STRING, 
      validate:{ 
       notEmpty:{ 
        args:true, 
        msg:"Email-id required" 
       }, 
       isEmail:{ 
        args:true, 
        msg:'Valid email-id required' 
       } 
      }, 
      unique: { 
       args:true, 
       msg: 'Email address already in use!' 
      } 

     } 

其他所有验证工作正常,除了unique电子邮件validion

+0

您是否在电子邮件字段中添加了唯一索引? –

+1

是它的唯一索引 – Jabaa

回答

0

尝试这

email:{ 
     type:Sequelize.STRING, 
     validate:{ 
      notEmpty:{ 
       args:true, 
       msg:"Email-id required" 
      }, 
      isEmail:{ 
       args:true, 
       msg:'Valid email-id required' 
      } 
     }, 
     unique: { msg: 'Email address already in use!' } 

    } 
+0

它没有工作, – Jabaa

+0

这个规则从来没有解雇,但所有其他规则工作正常 – Jabaa

2

我有同样的问题,要解决这个我第一次加入到索引模型的表:

queryInterface.addIndex('users', ['email'], { 
     indexName: 'email', 
     indicesType: 'UNIQUE' 
    }) 

并设置其名称等于该字段,因为如果你不这样做,它将默认创建一个,并且该模型将无法使用它。

email: { 
    type: Sequelize.STRING(191), 
    allowNull: false, 
    unique: { 
     msg: 'your-message-here' 
    } 
}, 

我不知道这是否是在sequelize或错误与我使用的版本有问题,但它只有在我设置索引名作为同一领域的工作。

+0

不得不添加索引,使其工作...像这样'sequelize.define('用户',{。 ..},{indexes:[{unique:true,fields:[“email”]}]});' –

0
email: { 
     type : DataTypes.STRING, 
     validate : { 
     isEmail: { 
      msg: "wrong format email" 
     }, 
     notEmpty: { 
      msg: 'Email not null' 
     }, 
     isUnique: function(value, next){ 

      'table'.find({ 
      where : { 
       email:value, 
       id:{[Op.ne]: this.id} 
      } 
      }).then(function(result){ 
      if(result === null){ 

       return next() 

      }else{ 
       return next(' Email already use') 
      } 
      }).catch(err =>{ 
       return next() 
      }) 
     } 
     } 
    } 
+0

我觉得内建函数已经有了那个db用来寻找唯一的方法,然后触发你自己的查询。 –