Unable to get Sequelize check

I am trying to test 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 try to create an instance and test it:

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

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

How to use validate() correctly?

+8
source share
3 answers

Here's how to solve your problem 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 lead to:

 { from: [ 'Invalid email' ] } 

Note: you can also skip validate -call and just instantiate 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 same error object as in the previous code fragment.

Hi sdepold.

+6
source share

An alternative approach for validation in Sequelize is to use a hook instead of model validation. I use the "beforeValidate" hook and add a special check (using the check module) with Promises, which are rejected if the check 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; }; 
+5
source share

It worked for me
The model uses: -

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

In your control logic, when saving the model, do the following: -

 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 }); 
+5
source share

All Articles