这是因为 Joi 默认提前中止。
abortEarly - 当true 时,对第一个错误停止验证,否则返回找到的所有错误。默认为true。
*编辑: hapi 8.0 中的配置已更改。您需要将abortEarly: false 添加到routes 配置中:
var server = new Hapi.Server();
server.connection({
host: 'localhost',
port: 8000,
routes: {
validate: {
options: {
abortEarly: false
}
}
}
});
*有关详细信息,请参阅Joi API documentation。
*另外,请参阅Hapi Route options 下的validation。
所以 Joi 在第一个错误时停止验证:
var Hapi = require('hapi');
var Joi = require('joi');
var server = new Hapi.Server('localhost', 8000);
server.route({
method: 'GET',
path: '/{first}/{second}',
config: {
validate: {
params: {
first: Joi.string().max(5),
second: Joi.string().max(5)
}
}
},
handler: function (request, reply) {
reply('example');
}
});
server.start();
server.inject('/invalid/invalid', function (res) {
console.log(res.result);
});
输出:
{ statusCode: 400,
error: 'Bad Request',
message: 'first length must be less than or equal to 5 characters long',
validation: { source: 'params', keys: [ 'first' ] } }
但是,您可以将 Hapi 配置为返回所有错误。为此,您需要将abortEarly 设置为false。您可以在服务器配置中执行此操作:
var server = new Hapi.Server('localhost', 8000, { validation: { abortEarly: false } });
如果你现在运行脚本,你会得到:
{ statusCode: 400,
error: 'Bad Request',
message: 'first length must be less than or equal to 5 characters long. second length must be less than or equal to 5 characters long',
validation: { source: 'params', keys: [ 'first', 'second' ] } }