2014-09-20 79 views
8

我有一個由名稱字段,電子郵件字段和textarea組成的三字段表單。我正在使用Joi 4.7.0版本以及hapijs。我使用下面的對象驗證輸入。我從ajax調用接收數據對象。當我用錯誤的信息填充所有三個字段時,我只收到與第一個錯誤字段相關的消息。這樣的:Joi驗證只返回一個錯誤信息

"{"statusCode":400,"error":"Bad Request","message":"name is not allowed to be empty","validation": {"source":"payload","keys":["data.name"]}}" 

validate: { 
     payload: { 
     data: { 
      name: Joi.string().min(3).max(20).required(), 
      email: Joi.string().email().required(), 
      message: Joi.string().min(3).max(1000).required() 
     } 
     } 
} 

爲了說明,我們假設以不填三個領域。我只收到一條消息錯誤,而不是其他字段的消息錯誤。爲什麼?

回答

17

這是因爲Joi在默認情況下提前中止。

abortEarly - when true , stops validation on the first error, otherwise returns all the errors found. Defaults to true .

*編輯:配置在高致病性禽流感發生8.0已經改變。您需要添加abortEarly: falseroutes配置:

var server = new Hapi.Server(); 
server.connection({ 
    host: 'localhost', 
    port: 8000, 
    routes: { 
     validate: { 
      options: { 
       abortEarly: false 
      } 
     } 
    } 
}); 

*請參閱Joi API documentation瞭解更多詳情。
*另請參閱validationHapi 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' ] } } 
4

validation鍵不再與Hapi.Server構造工程哈皮8.0:

[1] validation is not allowed

我在GitHub issue for hapi找到了解決方案:

var Hapi = require('hapi'); 


var server = new Hapi.Server(); 

server.connection({ 
    host: HOST, 
    port: PORT, 
    routes: { 
    validate: { 
     options: { 
     abortEarly: false 
     } 
    } 
    } 
}); 

// Route using Joi goes here. 
server.route({}); 

server.start(function() { 
    console.log('Listening on %s', server.info.uri); 
}); 
3

我沒有與hapi.js集成,但我注意到有一個ValidationOptions對象可以傳遞。裏面那個對象是abortEarly選項,所以這應該工作:

Joi.validate(request, schema, {abortEarly: false}

這也可以被配置如下:

Joi.object().options({ abortEarly: false }).keys({...}); 

檢查出更多的ValidationOptions這些類型定義: https://github.com/DefinitelyTyped/tsd/blob/master/typings/joi/joi.d.ts