Skip to content

Commit 20e2248

Browse files
authored
Merge pull request #4 from 2bit-hack/master
Implement Form Validation at Backend Register
2 parents f0bc197 + 303630e commit 20e2248

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

routes/api/users.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,23 @@ const jwt = require("jsonwebtoken");
55

66
const User = require("../../models/user");
77

8+
const { validatePassword, validateEmail } = require("../../validators/validators");
9+
810
router.post("/", async (req, res) => {
911
const { name, email, password } = req.body;
1012

1113
if (!name || !email || !password) {
1214
return res.status(400).send({ msg: "Please enter all fields" });
1315
}
1416

17+
if (!validateEmail(email)) {
18+
return res.status(400).send({ msg: "Invalid email address format specified" });
19+
}
20+
21+
if (!validatePassword(password)) {
22+
return res.status(400).send({ msg: "Password must be at least 8 characters in length and must contain at least 1 lowercase letter, 1 uppercase letter, 1 numeric digit, and 1 special character" });
23+
}
24+
1525
const existingUser = await User.findOne({ email });
1626
if (existingUser) {
1727
res.status(400).send({ msg: "Already registered user with this email" });

validators/validators.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
const validatePassword = (password) => {
2+
// 1 special character
3+
// 1 digit
4+
// 1 lowercase character
5+
// 1 uppercase character
6+
const passwordRegex = /^(?=.*[^A-Za-z0-9])(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/;
7+
8+
return passwordRegex.test(password);
9+
};
10+
11+
const validateEmail = (email) => {
12+
// from https://emailregex.com/
13+
// claims to match 99.99% of all email addresses
14+
const emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
15+
16+
return emailRegex.test(email);
17+
};
18+
19+
module.exports = {
20+
validatePassword,
21+
validateEmail,
22+
};

0 commit comments

Comments
 (0)