hapijs joi电子邮件验证选项tldWhitelist用法

时间:2015-11-03 22:09:00

标签: node.js validation email hapijs joi

我正在尝试使用Joi和Hapijs来验证POST提交请求。

这是我的招摇代码:

  server.route([
    {
      method: "POST",
      path: '/cardsignup',
      config: {
        handler: card_signup,
        description: 'Insert card signup record',
        notes: 'save card signup to database',
        tags: ['card', 'signup', 'api'],
        plugins: {
          'hapi-swagger': {
            responseMessages: [
              {code: 200, message: 'Success'},
              {code: 400, message: 'Bad Request'},
              {code: 401, message: 'Not Authorized'},
              {code: 500, message: 'Internal Server Error'}
            ]
          }
        },
        validate: {
          payload: {
            name: Joi.string()
              .required()
              .description('full name'),
            email: Joi.string().email({
              tldWhitelist:['example.com']
            })
              .required()
              .description('email'),
            signature_svg: Joi.string()
              .optional()
              .description('string encoded svg'),
            signature_png: Joi.binary()
              .optional()
              .description('base64 encoded png'),
            card_choice: Joi.string()
              .required()
              .description('card choice string'),
            last4: Joi.number()
              .required()
              .description('last 4 digits of cc')
          }
        }
      }
    }
  ]);

当我对服务器进行POST时,无论发送什么电子邮件,我都会收到回复:

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": "child \"email\" fails because [\"email\" must be a valid email]",
  "validation": {
    "source": "payload",
    "keys": [
      "email"
    ]
  }
}

有人有一个如何使用tldWhitelist的例子吗?

具体来说,我想验证电子邮件来自example.com

1 个答案:

答案 0 :(得分:2)

tldWhitelist的值可以是对象查找表,也可以是有效顶级域的数组。例如:

tldWhitelist: ['com']