Next.js Discord

Discord Forum

Best approach on data validation?

Answered
Glaucous-winged Gull posted this in #help-forum
Open in Discord
Glaucous-winged GullOP
Hi! I'm developing a nextjs project for learning purposes. I'm making some api endpoints where I expect a client post request with a body with a specific json format. A simple example:
import { NextApiRequest, NextApiResponse } from "next";

interface User {
    username: string;
    email: string;
    password: string;
    nickname: string;
}

export default async function handler(
    req: NextApiRequest,
    res: NextApiResponse
) {
    switch (req.method) {
        case "POST":
            let user = req.body
            // Some data validation
            valida_data(user);

            res.status(200).json({ message: "Hello World" });
            break;
        default:
            res.setHeader("Allow", ["GET"]);
            res.status(405).end(`Method ${req.method} Not Allowed`);
    }
}

How would I validate that the username, email, password and nickname are not null or empty strings?
I know I could define a function like:
function validateData(user: User): string | null {
    if (!user.username || user.username.trim() === "") return "Username is required";
    if (!user.email || user.email.trim() === "") return "Email is required";
    if (!user.password || user.password.trim() === "") return "Password is required";
    if (!user.nickname || user.nickname.trim() === "") return "Nickname is required";
    return null;
}

But that doesn't look to clean or reusable? Idk maybe i'm nit picking
Answered by Glaucous-winged Gull
I found about joi so I'll use that
View full answer

3 Replies

Glaucous-winged GullOP
I found about joi so I'll use that
Answer
Glaucous-winged GullOP
but thanks for the response!