Mongoose中的动态验证错误消息

时间:2018-01-14 06:15:25

标签: node.js mongodb validation mongoose mongoose-schema

我正在尝试验证instructionsRecipeSchema是否为有效的html字符串。为此我正在使用名为html-validator的包。我想传递这样的包返回的错误作为验证错误消息,而不是像"HTML is not valid"

那样的“静态”消息

我的代码:

const RecipeSchema = new Schema({
  instructions: {
    type: String,
    validate: {
      validator: instructions => {
        let isValid = false

        const options = {
          data: instructions,
          ignore: [
            'Error: Element “head” is missing a required instance of child element “title”.',
            'Error: Start tag seen without seeing a doctype first. Expected “<!DOCTYPE html>”.',
          ],
        }

        htmlValidator(options).then(data => {
          if (data === 'The document validates according to the specified schema(s).') {
            isValid = true
          } else {
            //  data is equal to the message I actually want to use
          }
        })

        return isValid
      },
      message: 'Oops, the provided HTML is not valid',  // this is static but shouldn't be!
    },
    required: 'Please enter some instructions for this recipe', 
  },
})  

1 个答案:

答案 0 :(得分:1)

在这种情况下,您可以使用回调作为验证器函数的第二个参数。

从Mongoose文档中的自定义验证的an example开始,您可以将两个参数传递给验证器函数,第一个参数是布尔值,验证器是否成功,第二个参数是可选的错误消息覆盖:

validate: {
  isAsync: true, // to avoid deprecation warnings
  validator: (instructions, cb) => {  // callback as second argument
    let isValid = false

    const options = {
      data: instructions,
      ignore: [
        'Error: Element “head” is missing a required instance of child element “title”.',
        'Error: Start tag seen without seeing a doctype first. Expected “<!DOCTYPE html>”.',
       ],
     }

     htmlValidator(options).then(data => {
       if (data === 'The document validates according to the specified schema(s).') {
         isValid = true
       }
       cb(isValid, data) // data is equal to the message I actually want to use
     })

    // return isValid
  },
  message: 'Oops, the provided HTML is not valid', // default message
}

而且我非常确定你可以尝试使用Promises而不是回调来使你的代码变得更干净。