How can I resolve Joi validation in String?

38 views Asked by At

I did validation for Json String, but I got an arror. Do You know how to resolve this? Error from Postman

I want to get validation error for example, "Title is missing"

I posted code from two files.

validator.ts

import dbConnect from "@/lib/dbConnect";
import { postValidationSchema, validateSchema } from "@/lib/validator";
import Joi from "joi";
import { NextApiHandler } from "next";

const handler: NextApiHandler = async (req, res) => {
    const { method } = req;
    switch(method){
        case 'GET': {
            await dbConnect();
            res.json({ok: true});
        }
        case 'POST': return createNewPost(req, res);
    }
};
const createNewPost: NextApiHandler = (req, res) => {
    const { body } = req;
    const error = validateSchema(postValidationSchema, body);
    if(error) return res.status(400).json({ error });
    res.json({ok: true});
};

export default handler;

index.ts

import Joi, {ObjectSchema} from "joi";

export const errorMessages = {
    INVALID_TITLE: "Title is missing!",
    INVALID_TAGS: "Tags must be array of strings!",
    INVALID_SLUG: "Slug is missing!",
    INVALID_META: "Meta description is missing!",
    INVALID_CONTENT: "Post content is missing!",
};

export const postValidationSchema = Joi.object().keys({
    title: Joi.string().required().messages({
        'string.empty': errorMessages.INVALID_TITLE,
        'any.required': errorMessages.INVALID_TITLE,
    }),
})

export const validateSchema = (schema: ObjectSchema , value: any) => {
    const { error } = schema.validate(value, {
        errors: { label: "key", wrap: { label: false, array: false } },
        allowUnknown: true,
    });

    if(error) return error.details[0].message;

    return '';
    
}
0

There are 0 answers