0
0
Expressframework~5 mins

Schema validation in Express

Choose your learning style9 modes available
Introduction

Schema validation helps check if the data sent to your server is correct and safe before using it.

When a user submits a form and you want to check the data format.
When receiving data from an API client to ensure it matches expected rules.
When saving data to a database and you want to avoid errors or bad data.
When you want to give clear error messages if data is missing or wrong.
Syntax
Express
const schema = Joi.object({
  name: Joi.string().required(),
  age: Joi.number().integer().min(0)
});

const { error, value } = schema.validate(data);
Use a library like Joi to define the schema rules clearly.
The validate method returns an error if data does not match the schema.
Examples
This schema checks that the email field is a valid email string and is required.
Express
const schema = Joi.object({
  email: Joi.string().email().required()
});
This schema ensures the password is at least 6 characters long and must be provided.
Express
const schema = Joi.object({
  password: Joi.string().min(6).required()
});
This schema checks that age is a whole number between 18 and 99.
Express
const schema = Joi.object({
  age: Joi.number().integer().min(18).max(99)
});
Sample Program

This Express server listens for POST requests to /register. It checks the request body against the userSchema. If the data is wrong, it sends back an error message. If correct, it confirms the data is valid.

Express
import express from 'express';
import Joi from 'joi';

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

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

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

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

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

Joi is a popular library for schema validation in Express apps.

Validation errors help users fix their input by showing clear messages.

Summary

Schema validation checks data matches rules before using it.

Use libraries like Joi to define and run these checks easily.

Validation improves app safety and user experience.