marvin_yorke
marvin_yorke

Reputation: 3559

Cannot get Sequelize validation working

I'm trying to implement validation in my Sequelize models. The model is defined as follows

var model = sequelize.define('Model', {
  from: {
    type:               DataTypes.STRING,
    allowNull:          false,
    validate: {
      isEmail: true
    }
  }
}

Then I'm trying to build an instance and validate it:

var m = Model.build({ from: 'obviously not a email' });
var err = m.validate();

But if I do console.log(err), I get { fct: [Function] } only. Defining a custom validator that throws an exception results in an unhandled exception.

How should I use validate() properly?

Upvotes: 10

Views: 25543

Answers (3)

Keval
Keval

Reputation: 3326

This worked for me
In model use :-

var model = sequelize.define('Model', {
  from: {
    type:               DataTypes.STRING,
    allowNull:          false,
    validate: {
      isEmail: true
    }
  }
}

In your control logic while you save model do this :-

var Sequelize = require('sequelize');
var Model = require('your_model_folderpath').model;

Model.create({from: 'not email'}).then(function(model) {
                    // if validation passes you will get saved model
            }).catch(Sequelize.ValidationError, function(err) {
                    // responds with validation errors
            }).catch(function(err) {
                    // every other error
            });

Upvotes: 5

William Myers
William Myers

Reputation: 297

An alternative approach for validating in Sequelize, use a hook instead of a model validation. I'm using the 'beforeValidate' hook and adding custom validation (using validator module) with Promises that are rejected when validation fails.

var validator = require('validator');

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define("User", {
    email: {
      type:DataTypes.STRING
    },
    password: {
      type:DataTypes.STRING
    }
  });
  //validate here
  User.hook('beforeValidate', function(user, options) {
    if(validator.isEmail(user.email)){
      return sequelize.Promise.resolve(user);
    }else{
      return sequelize.Promise.reject('Validation Error: invalid email');
    }
 });
 return User;
};

Upvotes: 5

sdepold
sdepold

Reputation: 6231

Here is how to get your problem solved with Sequelize v2.0.0:

var Sequelize = require("sequelize")
  , sequelize = new Sequelize("sequelize_test", "root")

var Model = sequelize.define('Model', {
  from: {
    type:      Sequelize.STRING,
    allowNull: false,
    validate:  {
      isEmail: true
    }
  }
})

Model.sync().success(function() {
  Model.build({ from: "foo@bar" }).validate().success(function(errors) {
    console.log(errors)
  })
})

This will result in:

{ from: [ 'Invalid email' ] }

Side note: You can also skip the validate-call and just create the instance instead:

Model.sync().success(function() {
  Model
    .create({ from: "foo@bar" })
    .success(function() {
      console.log('ok')
    })
    .error(function(errors) {
      console.log(errors)
    })
})

The error method will receive the very same error object as in the previous code snippet.

Greetings, sdepold.

Upvotes: 11

Related Questions