Validate only when value is changing

Viewed 99

I'm using Sequelize 4.38.0 and have the custom validation for email on the User model.

The way the custom validation is constructed (see below), I need to skip the validation if the email property hasn't changed. Otherwise it halts the whole update operation (as it thinks the email address is already taken).

How can I run validation for a property only when the value is changing?

email: {
  type: DataTypes.STRING,
  allowNull: false,
  validate: {
    isEmail: {
      msg: 'Wrong email format',
    },
    notEmpty: {
      msg: 'Email has to be present',
    },
    isUnique: function(value, next) {
      User.find({
        where: {
          email: value,
          organizationId: this.organizationId,
        },
      })
        .then(function(result) {
          if (result === null) {
            return next()
          } else {
            return next(' Email address already in use')
          }
        })
        .catch(err => {
          return next()
        })
    },
  },
},
1 Answers

Solved it with a conditional like this:

isUnique: function(value, next) {
  if (this.changed('email')) {
    User.find({
      where: {
        email: value,
        organizationId: this.organizationId,
      },
    })
      .then(function(result) {
        if (result === null) {
          return next()
        } else {
          return next(' Email address already in use')
        }
      })
      .catch(err => {
        return next()
      })
  } else {
    next()
  }
},
Related