2016-06-29 1 views
1

빠른 데이터 유효성 검사를 사용하고 있습니다. 좋습니다. 그러나 일부 데이터는 유효성 검사를 사용하여 확인하는 것이 실제적이지 않습니다 (예 : 페이스 북 토큰이 유효한지 확인하는 경우)req.validationErrors()에 사용자 정의 오류를 추가 하시겠습니까?

내가 생각할 수 없거나 최소한 할 수있는 유효성 검사를 수행 할 수있는 방법이 있습니까? 어떻게 든 수동으로 객체 등을 전달하여 오류를 추가합니까?

auth = (req, res, next) => { 
    //some setup: 
    res.locals.errors = []; 
    passport.authenticate('facebook-token', (err, user, info) => { 
     //this is where I would like to either validate with a custom validation or add this manually to whereever validationErrors get's it's values. 
     if(err && err.message === "Failed to fetch user profile"){ 
      res.locals.errors.push({ 
       param: 'access_token', 
       msg: 'Invalid access token', 
       value: req.query.access_token 
      }); 
     } 

    })(req, res, next); 
}, 

답변

0

동일한 문제가 발생했습니다. 익스프레스 유효성 검사기에서 생성 한 배열에 오류를 추가하여 req.validationErrors()을 호출 할 때 오류가 표시되도록하고 싶습니다.

그러나 필자가 원했던 유효성 검사는 특정 매개 변수 나 헤더에 대한 빠른 형식 검사 이상이었습니다. 한 번에 여러 필드를 검사하고 실패한 오류를 표준 validationErrors 배열로 밀어 넣고 싶었습니다.

express-validator을 사용하여 'customValidator'를 추가하여이 작업을 수행했습니다. 내 사용자 정의 유효성 검사기 항상 반환 거짓이 같은 내 사용자 지정 유효성 검사기를 주입

: 내 사용자 지정 논리가 실패 할 경우

이제
app.use(expressValidator({ 
customValidators: { 
    myCustomFunc: function(value) { 
     return false; 
    } 
} 
})); 

난 단지이 사용자 정의 유효성 검사기를 호출 -이이 설정의 영향을 validationErrors 배열의 오류입니다. express-validator는 유효한 param/header를 전달해야하기 때문에 나는 자신의 더미를 만들고 그 필드에서 false를 반환한다는 것을 알고있는 custom validator를 호출하기로 결정했다. 본질적으로 깃발로 사용하고 있습니다 :

// code to check for custom logic - needs reqeust object 
// in this simple example I check whether field2 is set if 
// we have field1 
function isValidRequest(req, cb){ 

    if(req.headers.myField1 && !req.headers.myField2){ 
    // create dummy header field 
    req.headers.myDummyHeader = false; 
    // now call customValidator, pass it our new dummy header 
    req.checkHeaders("myDummyHeader", 
    "Invalid request, myField1 and myField2 should both be set").myCustomFunc(); 
    } 

cb() 
} 

... 

// (later) get the express validation errors 
// you'll see that our custom error message is included 
var errors = req.validationErrors(); 
console.log(errors); 
관련 문제