简体   繁体   中英

Custom validation error message on hapi with joi

I'm implementing custom validation error message on hapi with joi.

    server.route({
        path: '/test/inputname',
        method: ['PUT','POST'],
        handler: async (request, h) => {
            try{
                const created =  await MemberSchema.addUser(
                    {"input_name": request.payload.input_name}
                )
                return h.response(created).code(201);
            } catch(err){
                console.log(err.message);
                return h.response(err.message).code(400);
            }
        },
        options: {
            validate: {
                payload: Joi.object({
                    input_name: Joi.string()
                        .min(2)
                        .max(30)
                        .required()
                        .messages({
                            'string.base' : `"input_name" should be a type of 'text'`,
                            'string.empty' : `"input_name" cannot be an empty field`,
                            'string.min' : `"input_name" should have a minimum length of {#limit}`,
                            'any.required' : `"input_name" is a required field`,
                        }),
                }),
                options:{
                    allowUnknown: true
                    ,abortEarly: false
                }
            }
        }
    });

However when I post invalid data, it always displayed as follows.

"statusCode": 400,
"error": "Bad Request",
"message": "Invalid request payload input"

How can it be solved?

ps I'm using the following version.

node v12.16.2
"@hapi/hapi": "^19.1.1",
"@hapi/joi": "^17.1.1",

FailAction might be required.

    options: {
        validate: {
            payload:  MemberSchema.memberSchema
            ,options:{
                allowUnknown: true
                ,abortEarly: false
            }
            ,failAction: async (request, h, err) => {
                console.log(err);
                throw err;
            }
        }
    },

Then message changed as follows.

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "\"input_name\" should have a minimum length of 2",
    "validation": {
        "source": "payload",
        "keys": [
            "input_name"
        ]
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM