這是因爲Joi在默認情況下提前中止。
abortEarly
- when true
, stops validation on the first error, otherwise returns all the errors found. Defaults to true
.
*編輯:配置在高致病性禽流感發生8.0已經改變。您需要添加abortEarly: false
到routes
配置:
var server = new Hapi.Server();
server.connection({
host: 'localhost',
port: 8000,
routes: {
validate: {
options: {
abortEarly: false
}
}
}
});
*請參閱Joi API documentation瞭解更多詳情。
*另請參閱validation
的Hapi Route options。
所以穰停止驗證上的第一個錯誤:
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' ] } }
但是,您可以配置哈皮返回的所有錯誤。爲此,您需要將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' ] } }