How to use the express-validator.sanitizeBody function in express-validator

To help you get started, we’ve selected a few express-validator examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nerdeveloper / hackathon-starter-kit / src / routes / index.ts View on Github external
};
}

router.get("/", indexController.home);
router.get("/contact", indexController.contact);
router.get("/404", indexController.notFound);

router.post(
    "/contact",
    [
        /**Check the form and validated it before submitting  */
        sanitizeBody("name"),
        check("name", "Name cannot be blank")
            .not()
            .isEmpty(),
        sanitizeBody("surname"),
        check("surname", "Name cannot be blank")
            .not()
            .isEmpty(),
        check("need", "Your framework cannot be empty")
            .not()
            .isEmpty(),
        check("email", "Email is not valid").isEmail(),
        check("email").normalizeEmail({
            gmail_remove_subaddress: false, // correct
            outlookdotcom_remove_subaddress: false,
            gmail_remove_dots: false,
            icloud_remove_subaddress: false,
        }),

        check("message", "Message cannot be blank")
            .not()
github maitraysuthar / rest-api-nodejs-mongodb / controllers / AuthController.js View on Github external
body("firstName").isLength({ min: 1 }).trim().withMessage("First name must be specified.")
		.isAlphanumeric().withMessage("First name has non-alphanumeric characters."),
	body("lastName").isLength({ min: 1 }).trim().withMessage("Last name must be specified.")
		.isAlphanumeric().withMessage("Last name has non-alphanumeric characters."),
	body("email").isLength({ min: 1 }).trim().withMessage("Email must be specified.")
		.isEmail().withMessage("Email must be a valid email address.").custom((value) => {
			return UserModel.findOne({email : value}).then((user) => {
				if (user) {
					return Promise.reject("E-mail already in use");
				}
			});
		}),
	body("password").isLength({ min: 6 }).trim().withMessage("Password must be 6 characters or greater."),
	// Sanitize fields.
	sanitizeBody("firstName").escape(),
	sanitizeBody("lastName").escape(),
	sanitizeBody("email").escape(),
	sanitizeBody("password").escape(),
	// Process request after validation and sanitization.
	(req, res) => {
		try {
			// Extract the validation errors from a request.
			const errors = validationResult(req);
			if (!errors.isEmpty()) {
				// Display sanitized values/errors messages.
				return apiResponse.validationErrorWithData(res, "Validation Error.", errors.array());
			}else {
				//hash input password
				bcrypt.hash(req.body.password,10,function(err, hash) {
					// generate OTP for confirmation
					let otp = utility.randomNumber(4);
					// Create User object with escaped and trimmed data
github maitraysuthar / rest-api-nodejs-mongodb / controllers / AuthController.js View on Github external
body("lastName").isLength({ min: 1 }).trim().withMessage("Last name must be specified.")
		.isAlphanumeric().withMessage("Last name has non-alphanumeric characters."),
	body("email").isLength({ min: 1 }).trim().withMessage("Email must be specified.")
		.isEmail().withMessage("Email must be a valid email address.").custom((value) => {
			return UserModel.findOne({email : value}).then((user) => {
				if (user) {
					return Promise.reject("E-mail already in use");
				}
			});
		}),
	body("password").isLength({ min: 6 }).trim().withMessage("Password must be 6 characters or greater."),
	// Sanitize fields.
	sanitizeBody("firstName").escape(),
	sanitizeBody("lastName").escape(),
	sanitizeBody("email").escape(),
	sanitizeBody("password").escape(),
	// Process request after validation and sanitization.
	(req, res) => {
		try {
			// Extract the validation errors from a request.
			const errors = validationResult(req);
			if (!errors.isEmpty()) {
				// Display sanitized values/errors messages.
				return apiResponse.validationErrorWithData(res, "Validation Error.", errors.array());
			}else {
				//hash input password
				bcrypt.hash(req.body.password,10,function(err, hash) {
					// generate OTP for confirmation
					let otp = utility.randomNumber(4);
					// Create User object with escaped and trimmed data
					var user = new UserModel(
						{
github nerdeveloper / hackathon-starter-kit / src / routes / index.ts View on Github external
function wrapAsync(fn: any) {
    return function(req: Request, res: Response, next: NextFunction) {
        fn(req, res, next).catch(next);
    };
}

router.get("/", indexController.home);
router.get("/contact", indexController.contact);
router.get("/404", indexController.notFound);

router.post(
    "/contact",
    [
        /**Check the form and validated it before submitting  */
        sanitizeBody("name"),
        check("name", "Name cannot be blank")
            .not()
            .isEmpty(),
        sanitizeBody("surname"),
        check("surname", "Name cannot be blank")
            .not()
            .isEmpty(),
        check("need", "Your framework cannot be empty")
            .not()
            .isEmpty(),
        check("email", "Email is not valid").isEmail(),
        check("email").normalizeEmail({
            gmail_remove_subaddress: false, // correct
            outlookdotcom_remove_subaddress: false,
            gmail_remove_dots: false,
            icloud_remove_subaddress: false,
github maitraysuthar / rest-api-nodejs-mongodb / controllers / AuthController.js View on Github external
.isAlphanumeric().withMessage("First name has non-alphanumeric characters."),
	body("lastName").isLength({ min: 1 }).trim().withMessage("Last name must be specified.")
		.isAlphanumeric().withMessage("Last name has non-alphanumeric characters."),
	body("email").isLength({ min: 1 }).trim().withMessage("Email must be specified.")
		.isEmail().withMessage("Email must be a valid email address.").custom((value) => {
			return UserModel.findOne({email : value}).then((user) => {
				if (user) {
					return Promise.reject("E-mail already in use");
				}
			});
		}),
	body("password").isLength({ min: 6 }).trim().withMessage("Password must be 6 characters or greater."),
	// Sanitize fields.
	sanitizeBody("firstName").escape(),
	sanitizeBody("lastName").escape(),
	sanitizeBody("email").escape(),
	sanitizeBody("password").escape(),
	// Process request after validation and sanitization.
	(req, res) => {
		try {
			// Extract the validation errors from a request.
			const errors = validationResult(req);
			if (!errors.isEmpty()) {
				// Display sanitized values/errors messages.
				return apiResponse.validationErrorWithData(res, "Validation Error.", errors.array());
			}else {
				//hash input password
				bcrypt.hash(req.body.password,10,function(err, hash) {
					// generate OTP for confirmation
					let otp = utility.randomNumber(4);
					// Create User object with escaped and trimmed data
					var user = new UserModel(
github maitraysuthar / rest-api-nodejs-mongodb / controllers / AuthController.js View on Github external
// Validate fields.
	body("firstName").isLength({ min: 1 }).trim().withMessage("First name must be specified.")
		.isAlphanumeric().withMessage("First name has non-alphanumeric characters."),
	body("lastName").isLength({ min: 1 }).trim().withMessage("Last name must be specified.")
		.isAlphanumeric().withMessage("Last name has non-alphanumeric characters."),
	body("email").isLength({ min: 1 }).trim().withMessage("Email must be specified.")
		.isEmail().withMessage("Email must be a valid email address.").custom((value) => {
			return UserModel.findOne({email : value}).then((user) => {
				if (user) {
					return Promise.reject("E-mail already in use");
				}
			});
		}),
	body("password").isLength({ min: 6 }).trim().withMessage("Password must be 6 characters or greater."),
	// Sanitize fields.
	sanitizeBody("firstName").escape(),
	sanitizeBody("lastName").escape(),
	sanitizeBody("email").escape(),
	sanitizeBody("password").escape(),
	// Process request after validation and sanitization.
	(req, res) => {
		try {
			// Extract the validation errors from a request.
			const errors = validationResult(req);
			if (!errors.isEmpty()) {
				// Display sanitized values/errors messages.
				return apiResponse.validationErrorWithData(res, "Validation Error.", errors.array());
			}else {
				//hash input password
				bcrypt.hash(req.body.password,10,function(err, hash) {
					// generate OTP for confirmation
					let otp = utility.randomNumber(4);
github nerdeveloper / hackathon-starter-kit / src / routes / index.ts View on Github external
.isEmpty(),
    ],
    (req: Request, res: Response) => {
        wrapAsync(authController.registerForm(req, res));
    },
);

router.get("/logout", authController.logout);

router.get("/create", ensureLoggedIn("/login"), postController.addPost);

router.post(
    "/create",
    [
        /**Check the form and validated it before submitting  */
        sanitizeBody("title"),
        check("title", "Enter the title of your Post")
            .not()
            .isEmpty(),
        sanitizeBody("description"),
        check("description", "Enter the description of your Post")
            .not()
            .isEmpty(),
    ],
    (req: Request, res: Response) => {
        wrapAsync(postController.createPost(req, res));
    },
);

router.get("/posts", ensureLoggedIn("/login"), wrapAsync(postController.posts));

router.get("/create/:id/edit", ensureLoggedIn("/login"), wrapAsync(postController.editPost));
github maitraysuthar / rest-api-nodejs-mongodb / controllers / AuthController.js View on Github external
}];

/**
 * Verify Confirm otp.
 *
 * @param {string}      email
 * @param {string}      otp
 *
 * @returns {Object}
 */
exports.verifyConfirm = [
	body("email").isLength({ min: 1 }).trim().withMessage("Email must be specified.")
		.isEmail().withMessage("Email must be a valid email address."),
	body("otp").isLength({ min: 1 }).trim().withMessage("OTP must be specified."),
	sanitizeBody("email").escape(),
	sanitizeBody("otp").escape(),
	(req, res) => {
		try {
			const errors = validationResult(req);
			if (!errors.isEmpty()) {
				return apiResponse.validationErrorWithData(res, "Validation Error.", errors.array());
			}else {
				var query = {email : req.body.email};
				UserModel.findOne(query).then(user => {
					if (user) {
						//Check already confirm or not.
						if(!user.isConfirmed){
							//Check account confirmation.
							if(user.confirmOTP == req.body.otp){
								//Update user as confirmed
								UserModel.findOneAndUpdate(query, {
									isConfirmed: 1,
github maitraysuthar / rest-api-nodejs-mongodb / controllers / BookController.js View on Github external
* @param {string}      isbn
 * 
 * @returns {Object}
 */
exports.bookUpdate = [
	auth,
	body("title", "Title must not be empty.").isLength({ min: 1 }).trim(),
	body("description", "Description must not be empty.").isLength({ min: 1 }).trim(),
	body("isbn", "ISBN must not be empty").isLength({ min: 1 }).trim().custom((value,{req}) => {
		return Book.findOne({isbn : value,user: req.user._id, _id: { "$ne": req.params.id }}).then(book => {
			if (book) {
				return Promise.reject("Book already exist with this ISBN no.");
			}
		});
	}),
	sanitizeBody("*").escape(),
	(req, res) => {
		try {
			const errors = validationResult(req);
			var book = new Book(
				{ title: req.body.title,
					description: req.body.description,
					isbn: req.body.isbn,
					_id:req.params.id
				});

			if (!errors.isEmpty()) {
				return apiResponse.validationErrorWithData(res, "Validation Error.", errors.array());
			}
			else {
				if(!mongoose.Types.ObjectId.isValid(req.params.id)){
					return apiResponse.validationErrorWithData(res, "Invalid Error.", "Invalid ID");
github nerdeveloper / hackathon-starter-kit / src / routes / index.ts View on Github external
},
);

router.get("/logout", authController.logout);

router.get("/create", ensureLoggedIn("/login"), postController.addPost);

router.post(
    "/create",
    [
        /**Check the form and validated it before submitting  */
        sanitizeBody("title"),
        check("title", "Enter the title of your Post")
            .not()
            .isEmpty(),
        sanitizeBody("description"),
        check("description", "Enter the description of your Post")
            .not()
            .isEmpty(),
    ],
    (req: Request, res: Response) => {
        wrapAsync(postController.createPost(req, res));
    },
);

router.get("/posts", ensureLoggedIn("/login"), wrapAsync(postController.posts));

router.get("/create/:id/edit", ensureLoggedIn("/login"), wrapAsync(postController.editPost));
router.post("/create/:id", wrapAsync(postController.updatePost));
router.get("/create/:id/delete", wrapAsync(postController.deletePost));

export default router;