Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sequelize.js orm :Unique email validation for mysql not working

Here is my model validation for check email-id exists or not

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!'
            }

        }

All other validations are working fine except unique email validion

like image 975
Jabaa Avatar asked Oct 21 '25 15:10

Jabaa


2 Answers

I had the same issue, to solve this i first added to index to the model's table:

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

And sets its name equal to the field, because if you dont, it will create one by default and the model will not work with it.

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

I dont know if it is a bug on sequelize or a problem with version that i'm using, but it only worked after i set the index name as the same of the field.

like image 175
Matheus Bueno Avatar answered Oct 23 '25 06:10

Matheus Bueno


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()
          })
        }
      }
    }
like image 44
andrey amrulloh Avatar answered Oct 23 '25 04:10

andrey amrulloh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!