I would like to display my error message in my jade view after validation.
Jade
H1 Hello world
#error
p #{JSON.stringify(errorMsg)}
div
form(action="/",method="post")
div Foo
div
input(type="text",name="foo")
div
input(type="submit",name="submit")
This is my server code...
server.register(Vision,(err)=>{
if(err){console.log(err)}
server.views({
engines:{
jade:Jade
},
path: 'views',
relativeTo: __dirname });
server.route([
{
method:'GET',path:'/',
handler:(request,reply)=>{
reply.view('index');
}
},
{
method:'POST',path:'/',
handler: (request,reply) => {
console.log("POST '/' ");
const err = {}; // check error and set it
reply.view('index',{errorMsg:err});
},
config:{
validate:{
payload: {
foo: Joi.string().required(),
submit:Joi.string().required()
}
}
}
}
]); });
server.start((err)=>{
if(err){console.log(err);} console.log("server started:"+server.info.uri);
});
Goal is to validate the presence of foo
When the validation kicks in the server responses with a http 400 error which is totally fine and expected for api's. This happens even before the handler function is called.
What is the best way to handle validation error with using a view engine?
I was expecting something like (which is obviously not working)
if(request.error){
reply.view('index',{errorMsg:err});
}
I saw also some answers who dealed with the onPreResponse
event to catch it globally. Isn't their a way to do this in the request handler method?
Or any best practise tips?