0

在添加值之前,我必须检查名称是否已存在于数据库中。

所以,我决定添加 express 验证器自定义选项。这在创建调用中工作正常。但不能在更新调用中工作。这是我的代码

const { check, body } = require('express-validator/check'); var models = require("../models");

let Validations = [
    check('email').isEmail().withMessage("Invalid Email"),
    check('phone').isLength({ min: 5 }).withMessage("Min length Required"),
    check('name').not().isEmpty().withMessage("Value is Required"),
    body("name").custom(value => {
        return models.fundraisers.findByName(value).then(user => {
        if (user) {
            return Promise.reject('Name already in use');
        }
        })
    })
]

如何在更新调用中处理这个问题。

提前致谢。

4

1 回答 1

1

这是我的检查,它在创建和更新案例时效果很好:

check('name')
  .not().isEmpty()
  .isString()
  .custom(value => {
    return Group
      .findByName(value)
      .then(groups => {
        if(groups.length > 0) {
          return Promise.reject(value + '\'s already in use');
        }
      })
  })

顺便说一句,我只定义了 body-check :

const { check, validationResult } = require('express-validator/check');

希望能帮助到你 :)

于 2019-04-11T01:37:13.383 回答