So I am developing a signup route handler in Express with TypeScript. I am using express-validators
to avoid all this code I had to write out in my route handler, but in the documentation that I quickly scanned through, I do not see an example for username
, only for email
. Anyone with more experience know if I can get away with just implementing validation for just password
and passwordConfirmation
and just hard code validation for username
?
This is what I have thus far:
import express, { Request, Response } from "express";
import { body } from "express-validator";
const router = express.Router();
router.post(
"/auth/signup",
[
body("password")
.trim()
.isLength({ min: 4, max: 20 })
.withMessage("Must be between 4 and 20 characters"),
body("passwordConfirmation").custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error("Passwords must match");
}
}),
],
(req: Request, res: Response) => {
const { username, password, passwordConfirmation } = req.body;
// const existingUser = await usersRepo.getOneBy({ username });
// if (existingUser) {
// return res.status(422).send({ username: "Username already in use" });
// }
// const user = await usersRepo.create({
// username,
// password,
// passwordConfirmation,
// });
// req.session.userId = user.id;
// res.status(200).send({ username: req.body.username });
}
);
export { router as signupRouter };
Of course I am aware I am missing async
in front of the callback to use what is commented out.
Would what I have commented out work in the same environment as express-validators
?
You can validate either username and email using oneOf and by passing validationChains. Check the document with an example here
Go through this example for more clarification
const validation = [
oneOf([
check('useroremail')
.exists()
.withMessage('username is required')
.isLength({ min: 3 })
.withMessage('wrong username length'),
check('useroremail')
.exists()
.withMessage('Email is required')
.isEmail()
.withMessage('Email is not valid'),
]),
check('password')
.exists()
.withMessage('password is required')
];
function ValidationErrors(req, res, next) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log(util.inspect(errors.array()));
return res.status(422).json({ errors: errors.array() });
}
next();
};
router
.post('/', validation, ValidationErrors,
(req, res) =>
{
const isEmail = validator.isEmail(req.body.useroremail);
res.status(200).json({ isEmail });
});