express class validator
const express = require('express');
const { body, validationResult } = require('express-validator');
const app = express();
app.use(express.json());
app.post(
'/user',
[
body('username').isEmail(),
body('password').isLength({ min: 5 }),
body('confirmPassword').custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error('Password confirmation does not match password');
}
return true;
}),
],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Logic to handle valid user data
res.json({ success: true });
}
);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Explanation:
Import the necessary modules:
express
for creating the server, andbody
andvalidationResult
fromexpress-validator
for handling request body validation.Create an instance of the Express application.
Use
express.json()
middleware to parse incoming JSON requests.Define a POST route at the path '/user' that handles user registration.
Utilize the
body
function fromexpress-validator
to define validation checks for the 'username', 'password', and 'confirmPassword' fields in the request body.Use the
isEmail
validator to check if the 'username' field is a valid email.Use the
isLength
validator to check if the 'password' field has a minimum length of 5 characters.Use the
custom
validator for the 'confirmPassword' field to check if it matches the 'password' field.In the route handler function, use
validationResult
to check for validation errors. If errors are present, return a 400 status with the error details.If there are no validation errors, proceed with the logic to handle the valid user data. In this example, a success JSON response is sent.
Set up the server to listen on the specified port (either from the environment variable or default to 3000) and log a message indicating the server is running.