【问题标题】:how to validate request parameters in hapi and joi with regex如何使用正则表达式验证 hapi 和 joi 中的请求参数
【发布时间】:2018-05-25 19:09:33
【问题描述】:

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

【问题讨论】:

    标签: node.js validation hapijs


    【解决方案1】:

    试试这个:

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

    【讨论】:

      【解决方案2】:

      你可以这样使用

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

      【讨论】:

      • 感谢 Manjeet 的回答。它对我有用,希望这个问题对其他人也有帮助。
      • 现在它正在显示消息,例如“userName with value je$ failed to match the required pattern: /[a-zA-Z0-9{3,30}/]”。你能告诉我如何在那个地方设置我自己的自定义消息。
      • 我会尝试这种方法。感谢并投票支持我的问题,如果您认为这对其他人有帮助。
      猜你喜欢
      • 2020-09-19
      • 2015-10-17
      • 2019-08-03
      • 2021-04-20
      • 2018-09-24
      • 1970-01-01
      • 1970-01-01
      • 2013-10-19
      • 1970-01-01
      相关资源
      最近更新 更多