0
0
Expressframework~5 mins

Joi as validation alternative in Express

Choose your learning style9 modes available
Introduction

Joi helps you check if data is correct before using it. It makes sure your app gets good data and avoids errors.

When you want to check user input in forms before saving it.
When you receive data from an API and want to make sure it looks right.
When you want to avoid crashes caused by wrong or missing data.
When you want to give clear messages to users about what data is wrong.
When you want to keep your code clean by separating data checks from main logic.
Syntax
Express
const Joi = require('joi');

const schema = Joi.object({
  name: Joi.string().min(3).max(30).required(),
  age: Joi.number().integer().min(0).max(120),
  email: Joi.string().email().required()
});

const { error, value } = schema.validate(data);

Use Joi.object() to define the shape of your data.

Call schema.validate(data) to check data and get errors if any.

Examples
This checks if a string is at least 5 characters long and is present.
Express
const schema = Joi.string().min(5).required();
const { error } = schema.validate('hello');
This checks if a number is an integer between 1 and 10.
Express
const schema = Joi.number().integer().min(1).max(10);
const { error } = schema.validate(7);
This checks an object with username and password rules.
Express
const schema = Joi.object({
  username: Joi.string().alphanum().min(3).max(15).required(),
  password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$'))
});
const { error } = schema.validate({ username: 'user1', password: 'abc123' });
Sample Program

This Express app uses Joi to check user data sent to /user. If data is wrong, it sends an error message. If data is good, it confirms success.

Express
const express = require('express');
const Joi = require('joi');

const app = express();
app.use(express.json());

const userSchema = Joi.object({
  name: Joi.string().min(3).max(30).required(),
  email: Joi.string().email().required(),
  age: Joi.number().integer().min(0).max(120)
});

app.post('/user', (req, res) => {
  const { error, value } = userSchema.validate(req.body);
  if (error) {
    return res.status(400).send({ message: error.details[0].message });
  }
  res.send({ message: 'User data is valid', data: value });
});

app.listen(3000, () => console.log('Server running on port 3000'));
OutputSuccess
Important Notes

Joi gives detailed error messages to help fix data problems.

Always validate data before using it to keep your app safe.

You can customize Joi rules to fit your exact needs.

Summary

Joi helps check data easily and clearly.

Use Joi to avoid bugs from bad data.

It works well with Express to keep your app safe and clean.