-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidator.js
43 lines (39 loc) · 1.1 KB
/
validator.js
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
const conn = require("./db-connection").promise();
const { body, param, validationResult } = require("express-validator");
module.exports = {
// User name and email Validation
userInfo: [
body("name", "The name must be of minimum 3 characters length")
.optional()
.isLength({ min: 3 })
.trim()
.unescape()
.escape(),
body("email", "Invalid email address")
.optional()
.trim()
.unescape()
.escape()
.isEmail()
.custom(async (value) => {
// Checking that the email already in use or NOT
const [row] = await conn.execute(
"SELECT `email` FROM `users` WHERE `email`=?",
[value]
);
if (row.length > 0) {
return Promise.reject("E-mail already in use");
}
}),
],
// User ID Validation
userID: [param("id", "Invalid User ID").trim().isInt()],
// Checking Validation Result
result: (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
next();
},
};