如何使用正则表达式验证 hapi 和 joi 中的请求参数

how to validate request parameters in hapi and joi with regex

我是 hapi 的新手,我从简单的表单提交开始,需要验证我的表单数据。为此,我通过使用模块 "joi" 获得了功能。但是对于 joi 模型,我如何通过对用户名和密码等具有预先指定格式的字符串进行正则表达式验证来验证我的数据。

你可以这样使用

joi link on github
joi

var schema = Joi.object().keys({  
        username: Joi.string().regex(/[a-zA-Z0-9]{3,30}/).min(3).max(30).required(),
        password: Joi.string().regex(/[a-zA-Z0-9]{3,30}/),
        confirmation: Joi.ref('password')
      })
      .with('password', 'confirmation');

    // will fail because `foo` isn't in the schema at all
    Joi.validate({foo: 1}, schema, console.log);

    // will fail because `confirmation` is missing
    Joi.validate({username: 'alex', password: 'qwerty'}, schema, console.log);

    // will pass
    Joi.validate({  
      username: 'alex', password: 'qwerty', confirmation: 'qwerty'
    }, schema, console.log);

试试这个:

var Joi = require('joi')

server.route({  
  method: 'POST',
  path: '/',
  config: {
    handler: function (request, reply) {
      // do any processing

      reply('Your response data')
    },
    validate: {
      payload: {
        email: Joi.string().email().required(),
        password: Joi.string().min(6).max(200).required()
      }
    }
  }
})