Skip to content

Instantly share code, notes, and snippets.

@saman-ghm
Last active January 30, 2020 19:11
Show Gist options
  • Save saman-ghm/59c37e731aa18f34df67a10cd3283a1f to your computer and use it in GitHub Desktop.
Save saman-ghm/59c37e731aa18f34df67a10cd3283a1f to your computer and use it in GitHub Desktop.
validation entry
import { Router, Response, Request } from "express";
import express from "express";
import bodyParser from "body-parser";
class UserDto {
username: String;
password: String;
email: String;
}
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const router = Router();
router.post("/user/submit", async (req: Request, res: Response) => {
const { username, email, password } = req.body;
const passwordReg = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
const emailReg = /^(([^<>()\[\]\\.,;:\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,}))$/;
let validationError = false;
if (!username) {
res.status(400).send("username is required");
validationError = true;
}
if (!email) {
res.status(400).send("email is required");
validationError = true;
}
if (!password) {
res.status(400).send("password is required");
validationError = true;
}
if (!passwordReg.test(password)) {
res.status(400).send("password should contains at least one upper char, one lower char, one digit and 8 characters");
validationError = true;
}
if (!emailReg.test(email)) {
res.status(400).send("email is not valid");
validationError = true;
}
if (!validationError) {
const user = new UserDto();
user.username = username;
user.password = password;
user.email = email;
// pass 'user' object to repository/service
res.json({ username, email, password });
}
});
app.use(router);
app.listen(3000, () => {
console.log('Server is running in http://localhost:3000');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment