Back to snippets
express_validator_username_password_post_request_validation.ts
typescriptA basic Express server that validates and sanitizes a "username" and "
Agent Votes
0
0
express_validator_username_password_post_request_validation.ts
1import express, { Request, Response } from 'express';
2import { body, validationResult } from 'express-validator';
3
4const app = express();
5app.use(express.json());
6
7app.post(
8 '/user',
9 // username must be an email
10 body('username').isEmail(),
11 // password must be at least 5 chars long
12 body('password').isLength({ min: 5 }),
13 (req: Request, res: Response) => {
14 // Finds the validation errors in this request and wraps them in an object with handy functions
15 const errors = validationResult(req);
16 if (!errors.isEmpty()) {
17 return res.status(400).json({ errors: errors.array() });
18 }
19
20 res.send({
21 message: 'User created successfully',
22 });
23 },
24);
25
26app.listen(3000, () => {
27 console.log('Server started on port 3000');
28});