【发布时间】:2018-05-25 19:09:33
【问题描述】:
我是 hapi 新手,我从简单的表单提交开始,需要验证我的表单数据。为此,我通过使用模块“joi”获得了功能。但是使用 joi 模型,我如何通过对字符串(如用户名和密码)使用预先指定的格式进行正则表达式验证来验证我的数据。
【问题讨论】:
标签: node.js validation hapijs
我是 hapi 新手,我从简单的表单提交开始,需要验证我的表单数据。为此,我通过使用模块“joi”获得了功能。但是使用 joi 模型,我如何通过对字符串(如用户名和密码)使用预先指定的格式进行正则表达式验证来验证我的数据。
【问题讨论】:
标签: node.js validation hapijs
试试这个:
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()
}
}
}
})
【讨论】:
你可以这样使用
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);
【讨论】: