node.js 无法使 Sequelize 验证工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17253052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:52:52  来源:igfitidea点击:

Cannot get Sequelize validation working

node.jssequelize.js

提问by mrvn

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

我正在尝试在我的 Sequelize 模型中实现验证。模型定义如下

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.

但如果我这样做console.log(err),我{ fct: [Function] }只会得到。定义抛出异常的自定义验证器会导致未处理的异常。

How should I use validate()properly?

我应该如何validate()正确使用?

回答by sdepold

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

以下是如何使用 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:

旁注:您也可以跳过validate-call 而只是创建实例:

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.

error 方法将接收与前面的代码片段完全相同的错误对象。

Greetings, sdepold.

问候,sdepold。

回答by William Myers

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.

在 Sequelize 中进行验证的另一种方法是使用钩子而不是模型验证。我正在使用 'beforeValidate' 钩子并添加自定义验证(使用验证器模块)以及在验证失败时被拒绝的承诺。

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;
};

回答by Keval Gohil

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
            });