Data Validation
This uses Joi
library for validation.
Setup in models
In models
folder, as your create your TypeScript interface / type , you can create and export the Joi Schema for the same.
You can also use the interface your just created while writing the schema this way, to make sure it satisfies it correctly.
export const PostSchema = Joi.object<IPost>({ // ...documentFields, title: Joi.string().min(3).required().label('Title'), description: Joi.string(),})
This can throw build errors if it doesn't satisfy and you would know : )
Now this can be used in both Back-End API request validation and also Front-End form validation.
Let's see how to do in both environments...
Back End
In your controller you import the schema you created, and validate with request body this way (Atleast I recommended).
export const createPost: ApiHandler = async (req, res) => { const postData: IPost = req.body; await PostSchema.validateAsync(postData);
Because, if data not valid validateAsync
will throw and error. And this error is catched in our NextApiHandler
which recognize the error and tells client about which fields are wrong with status 400.
if (e instanceof Joi.ValidationError) { return res.status(400).json({ error: 'Validation Error', message: e.message, details: e.details, })}
There is also other way, but it doesn't throw the error. But worth mentioning as it might get used for another use case.
const { error, value } = postSchema.validate(data)if (error) { // invalid data} else { // do what you want}
Front-End
This blends well with react-hook-form
library, and you have to pass your schema as a resolver in useForm
hook this way:
const { control, ...methods } = useForm({ resolver: joiResolver(PostSchema),})
And there you have your cilent side validation ready.
You can refer the full Form example here client/components/PostForm.tsx
.