1

Hi guys I have a quick question Im using sequalize. and I created user model, that has field email, that has validation for emails like this

module.exports = (sequelize, DataTypes) => sequelize.define('user', {
    name: {
        type: DataTypes.STRING,
    },
    phone: {
        type: DataTypes.STRING,
    },
    email: {
        type: DataTypes.STRING,
        validate: {
            isEmail: true,
        },
    },
});

but sometimes in my app I would like to create user with no email, or email to be emtpy string... but validation doesnt allow me to .. is there any way in some cases to allow empty string to be saved as email, but in others to run validation ???

Loki
  • 1,064
  • 2
  • 26
  • 55

2 Answers2

6

Yes, You can try to create custom validator:

validateEmail = (email) => {
  var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(String(email).toLowerCase());
}

module.exports = (sequelize, DataTypes) => sequelize.define('user', {
  name: {
    type: DataTypes.STRING,
  },
  phone: {
    type: DataTypes.STRING,
  },
  email: {
    type: DataTypes.STRING,

    validate: {
      isEmailOrEmpty(val, next) {
        if (!val || val === "" || validateEmail(val)) {
          return next()
        }
        else {
          return next('email is invalid')
        }
      }
    }
  }
});

You just need Your own email validator (it is easy to find - example)

  • !val - check if value is present
  • val === "" - check if value is emptyString
  • validateEmail(val)) - validate email using regular expression
KarlR
  • 1,545
  • 12
  • 28
  • Thank you very much for your answer, And one more question for example if I dont want to call validateEmail function inside validate, and I would like to call isEmail of sequalize how could I do that ?? – Loki Aug 24 '18 at 12:43
  • Won't it suffice to simply set `allowNull: false` in the email field definition? – jayarjo Jul 03 '19 at 08:02
0

Use custom validator which contains isEmail() from sequelize.Validator:

email: {
    type: DataTypes.STRING,
    allowNull: true,
    validate: {
        isEmailOrEmpty: (value, next) => {
            if (!value) next() ;
            if (value !== '' && !sequelize.Validator.isEmail(value)) {
                throw new Error('Validation error: Email is invalid.');
            }
            next();
        }
    }
},