Support Online
Skip to main content

Express.js Form Security: Validation and Sanitization with Express-Validator

What will you learn in this guide?

In this guide, you will securely process user input using Express-Validator.
You will learn about form validation, data sanitization, and file upload security.
The aim is to reduce the risks of XSS and SQL Injection.

🧠 Technical Summary

The topic is secure processing of Express.js form data.
The problem is incorrect and harmful user input.
The solution is Express-Validator and Multer integration.


Preliminary Preparations

Before you start, you should have the following ready:

  • Node.js (v14 and above)
  • Express.js knowledge
  • JavaScript basics
  • VS Code or similar editor

1. Why Is Input Validation Necessary?

User input is a frequent target of attack.
Incorrectly processed forms create major security vulnerabilities.

Major risks:

  • SQL Injection
  • XSS attacks
  • Inconsistent data records

Validation and cleansing reduce these risks.


2. Basic Concepts

  • Validation: Checks whether the data complies with the rules
  • Sanitization: Cleans or transforms data
  • Validation Chain: Sequential validation and cleaning steps

3. Project Setup and Packages

mkdir express-form-guvenligi
cd express-form-guvenligi
npm init -y
npm install express express-validator
npm install --save-dev nodemon
  • These steps prepare the project structure.

4. Basic Form Validation Example


const express = require("express");
const { body, validationResult } = require("express-validator");

const app = express();
app.use(express.json());

app.post(
"/kayit-ol",
[
body("isim").notEmpty().withMessage("İsim alanı boş olamaz."),
body("email").isEmail().withMessage("Geçerli e-posta girin."),
body("sifre").isLength({ min: 6 }).withMessage("Şifre en az 6 karakter."),
],
(req, res) => {
const errors = validationResult(req);

if (!errors.isEmpty()) {
return res.status(400).json({ hatalar: errors.array() });
}

res.status(200).json({ mesaj: "Kayıt başarılı" });
}
);

app.listen(3000, () => {
console.log("Sunucu 3000 portunda çalışıyor");
});
  • This code validates form fields and prevents incorrect input.

5. Frequently Used Validators

ValidatorDescription
isEmailEmail format control
notEmptyNull value check
isLengthCharacter length control
isNumericNumerical data control
isURLURL verification
  • These rules can be chained.

6. File Upload Security (Multer)

6.1 Multer Installation


npm install multer
  • This package manages file uploading.

6.2 File Upload and Verification


const multer = require("multer");

const depolama = multer.diskStorage({
destination: "./yuklemeler/",
filename: (req, file, cb) => {
cb(null, Date.now() + "-" + file.originalname);
},
});

const yukleme = multer({
storage: depolama,
limits: { fileSize: 1024 * 1024 },
});

app.post(
"/dosya-yukle",
yukleme.single("profil_resmi"),
[body("aciklama").notEmpty()],
(req, res) => {
const errors = validationResult(req);

if (!req.file) {
return res.status(400).json({ hata: "Dosya seçilmedi." });
}

if (!errors.isEmpty()) {
return res.status(400).json({ hatalar: errors.array() });
}

res.status(200).json({ mesaj: "Dosya yüklendi" });
}
);
  • This structure limits file size and validates form fields.

7. Data Sanitization


app.post(
"/temiz-veri",
[
body("email").trim().isEmail().normalizeEmail(),
body("yorum").trim().escape(),
body("dogum_tarihi").toDate(),
],
(req, res) => {
res.json({ temiz_veri: req.body });
}
);
  • This code deletes spaces and cleans harmful content.

8. Validation Chain Logic

  1. More than one control can be applied to an area.

Example:

  • body("email").isEmail().trim().normalizeEmail()

  • This structure provides sequential control.


Frequently Asked Questions

  1. What is the difference between Validation and Sanitization? Validation checks. Sanitization changes data.

  2. Why is validationResult needed? Errors are not thrown automatically. Manual control required.

  3. Does this method prevent SQL Injection? Largely yes. Parameterized queries should also be used.

  4. Can a custom validator be written? Yes. The .custom() method can be used.


Result

In this guide, you have secured Express.js forms. With verification and sanitization, you have reduced the risks of attacks. This approach is the foundation of secure Node.js applications.

You can safely publish the projects you develop on the GenixNode infrastructure.