-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
89 lines (76 loc) · 2.6 KB
/
Copy pathapp.js
File metadata and controls
89 lines (76 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const express = require('express');
const { check, validationResult } = require('express-validator');
const app = express();
// Set EJS as the template view engine
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
// Middleware to parse form data
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// In-memory array to track registered emails
let usedEmails = [];
// GET route to render the initial empty registration form
app.get('/users', (req, res) => {
res.render('register', { errors: [], successMessage: null, formData: {} });
});
// POST route handling registration logic and validations
app.post('/users', [
// Part 1: Username Validations
check('username')
.notEmpty().withMessage('Username should not be empty')
.bail()
.isLength({ min: 4 }).withMessage('Username must be at least 4 characters long')
.bail()
.custom(value => !/\s/.test(value)).withMessage('Username should not include spaces'),
// Part 2: Email Validations
check('email')
.notEmpty().withMessage('Email should not be empty')
.bail()
.isEmail().withMessage('Invalid email')
.bail()
.custom(value => {
if (usedEmails.includes(value)) {
throw new Error('Email already exists');
}
return true;
}),
// Part 3: Password Validations
check('password')
.notEmpty().withMessage('Password should not be empty')
.bail()
.isLength({ min: 5 }).withMessage('Password must be at least 5 characters long')
.bail()
.matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/)
.withMessage('Password must contain a number, uppercase and lowercase'),
// Part 3: Confirm Password Custom Match Validation
check('confirmPassword')
.custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error('Passwords are not matching');
}
return true;
})
], (req, res) => {
const errors = validationResult(req);
// If validation fails, re-render form with errors and existing input data
if (!errors.isEmpty()) {
return res.render('register', {
errors: errors.array(),
successMessage: null,
formData: req.body
});
}
// Part 4: Successful validation actions
const { email } = req.body;
usedEmails.push(email);
return res.render('register', {
errors: [],
successMessage: "Congratulations, your account has been successfully created!",
formData: {} // Clear fields on success
});
});
// Start the server loop on port 3000
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running successfully on http://localhost:${PORT}/users`);
});