Input validation, sanitization, and preventing injection attacks

Learn how input validation and sanitization protect forms from injection attacks. Understand what makes form data safe.

Draft

When attackers target forms, they do not fill them out normally. Instead, they send code designed to break into your systems or steal data. They might submit JavaScript to run in visitors' browsers, SQL commands to break your database, or malicious content to cause damage. Input validation and sanitization are the defenses that stop these attacks.

What you'll learn: What input validation and sanitization are, how they differ, how injection attacks work, what protections work for different data types, and how to implement them on your forms.

What is input validation?

Input validation is the process of checking that data submitted to your form is in the format you expect and meets your requirements. It is the first line of defense against malicious input.

Validation answers questions such as whether this is an email address or random text, whether this is a number or a word, whether this field is empty when it should not be, and whether the visitor typed something that makes sense for this field or something suspicious.

Examples of what validation checks:

  • An email field should contain an @ symbol and a domain
  • A phone number field should contain only digits and hyphens
  • A number field should not contain letters
  • A required field should not be empty
  • A password field should meet minimum length requirements

Validation happens in two places. On the visitor's device, it is called client-side validation. On your server, it is called server-side validation. Client-side validation gives visitors immediate feedback if they make a mistake. Server-side validation is what actually protects against attacks, because attackers can bypass client-side checks.

What is input sanitization?

Sanitization is the process of removing or neutralizing anything dangerous from user input before you store or process it. Even if data passes validation, it might still contain code or characters designed to cause harm.

Examples of what sanitization does:

  • Removes HTML tags like `<script>` and `<img>` from text fields
  • Removes SQL special characters that could be used to break into databases
  • Escapes special characters so they are treated as text, not code
  • Limits the length of input to prevent buffer overflow attacks

Validation and sanitization work together but serve different purposes. Validation checks that the data is in the right format. Sanitization removes anything dangerous even if the format is technically correct.

How injection attacks work

SQL injection

A SQL injection attack happens when an attacker puts SQL code into a form field. If your form code does not sanitize this input, the SQL code gets executed on your database.

Example: A login form asks for an email address. Instead of submitting their email, an attacker submits:

' OR '1'='1

If your form does not sanitize this, your code might run a SQL query that looks like:

SELECT * FROM users WHERE email = '' OR '1'='1'

The `OR '1'='1'` part makes the condition always true, so the query returns all users instead of just the one with that email. The attacker has now bypassed the login system.

Cross-Site Scripting (XSS)

An XSS attack happens when an attacker submits JavaScript code in a form field. If the form does not sanitize this code and stores it, the JavaScript runs in the browsers of anyone who views that data later.

Example: A comment form accepts user comments. An attacker submits:

<script>alert('hacked')</script>

If this is not sanitized and is stored in the database, then when anyone views the comments section, the JavaScript runs and shows an alert. A more dangerous version could steal cookies, redirect visitors to a phishing page, or extract form data.

Command injection

If your form data is used in system commands (which happens in some backend systems), an attacker can inject operating system commands.

Example: A form field is used in a command like:

ffmpeg -i $filename output.mp4

If `$filename` is not sanitized and an attacker submits `;rm -rf /`, the command becomes:

ffmpeg -i ;rm -rf / output.mp4

The `rm -rf /` command runs and deletes files from the system. This is why system commands should never receive unsanitized user input.

Validation and sanitization for different data types

Email addresses

Validation: Check that the input matches an email pattern (something like text@domain.extension). Confirm it has only allowed characters.

Sanitization: Remove any HTML tags or special characters. Keep only alphanumeric characters, dots, hyphens, and the @ symbol.

Phone numbers

Validation: Check that it contains only digits, hyphens, parentheses, and spaces. Verify the length is correct for the expected country.

Sanitization: Remove any non-numeric characters except hyphens and parentheses. Strip leading zeros or spaces if needed.

Text fields (comments, names, addresses)

Validation: Check that the field is not empty, and that the length is reasonable (not millions of characters).

Sanitization: Remove or escape HTML tags, JavaScript, and SQL special characters. Keep only plain text and basic punctuation.

Numbers and amounts

Validation: Check that the input is a number. For prices or quantities, check that it is a positive number.

Sanitization: Remove any non-numeric characters. If needed, round to the correct decimal places.

Passwords

Validation: Check minimum length (at least 8 characters), and optionally require a mix of uppercase, lowercase, numbers, and symbols.

Sanitization: Do not strip or modify passwords. They should be stored in their exact form (hashed, never in plain text). If you strip characters from a password, users will not be able to log in.

File uploads

Validation: Check that the file type is what you expect (e.g., only PDF files, only images). Check the file size is not too large.

Sanitization: Rename the file so attackers cannot use special file names. Scan the file for malware. Store it outside the web root so it cannot be executed as code.

How to implement validation and sanitization

Client-side (in the browser)

Use HTML5 input validation attributes to provide immediate feedback to visitors:

<input type="email" name="email" required> <input type="tel" name="phone" pattern="[0-9]{10}"> <input type="number" name="age" min="0" max="120">

This catches obvious mistakes and improves the user experience. However, client-side validation can be bypassed, so it is not a security measure by itself.

Server-side (on your server)

This is where security happens. Your backend code must validate and sanitize every piece of data:

// Pseudo-code example if (email does not match email pattern) { reject the submission } // Remove HTML tags sanitized_comment = remove_html_tags(comment_text) // Escape special characters for database safe_name = escape_sql_characters(user_name) // Only then store the data store_in_database(safe_name, sanitized_comment)

Use parameterized queries for databases

The best defense against SQL injection is parameterized queries (also called prepared statements). Instead of putting user input directly into a SQL query, you use placeholders and pass the data separately:

// Bad (vulnerable): query = "SELECT * FROM users WHERE email = '" + email + "'" // Good (safe): query = "SELECT * FROM users WHERE email = ?" execute(query, [email])

With parameterized queries, the SQL parser knows that the user input is data, not code. Even if an attacker submits SQL code, it is treated as plain text.

Use libraries and frameworks

Do not write sanitization code from scratch. Use established libraries designed for this purpose. In PHP, use htmlspecialchars() or a library like HTML Purifier. In Python, use the `html` module or a library like bleach. In Node.js, use `express-validator` or similar. These libraries have been tested and updated to handle new attack types.

Common validation and sanitization mistakes

Only validating on the client side. Client-side validation is for user experience, not security. An attacker can bypass it. You must validate on the server too.

Blacklisting dangerous characters instead of whitelisting safe ones. If you try to block SQL injection by removing semicolons and quotes, attackers will find ways around it. Instead, whitelist the characters you expect (for phone numbers, allow only digits and hyphens) and reject everything else.

Trusting the data type of the form field. If you have a number field, the browser sends text that looks like a number. Your server must still verify it is actually a number before using it. Never assume the data type is correct.

Forgetting to sanitize data that is displayed. Even if data is stored safely, if you display it on a web page without escaping HTML, attackers can inject code that runs in visitors' browsers when they view that data.

Sanitizing in the wrong order. Validate first (is this the right format?), then sanitize (is this safe?). If you sanitize and then validate, you might reject data that was actually safe.

What WEMASY does for input validation

WEMASY validates form fields automatically based on the field type you choose. Email fields are checked for valid email format. Number fields are checked for numeric input. Required fields are checked for content before submission. On the server side, WEMASY sanitizes all input to remove HTML, JavaScript, and other dangerous code before storing submissions. You configure what fields to collect, and WEMASY handles validation and sanitization behind the scenes.

See what form features are included in your plan on the pricing page.

Frequently asked questions

Can I use a WAF (Web Application Firewall) instead of validation?
A WAF can catch some injection attacks before they reach your form, which is helpful. However, it is not a replacement for validation and sanitization. A WAF is a second line of defense. Your form code must still validate and sanitize data itself. Using both WAF and input validation gives you multiple layers of protection.
What if a visitor legitimately needs to submit special characters?
Special characters like apostrophes, hyphens, and ampersands are safe if you sanitize properly. For example, someone might have a name like "O'Brien" or "Mary-Jane". These are safe to accept if you escape them properly for your database (using parameterized queries) and when you display them (using HTML escaping). The key is proper sanitization, not blocking the characters.
Should I validate on both client and server?
Yes. Client-side validation gives visitors immediate feedback and improves the experience (they know they made a typo before submitting). Server-side validation is what actually protects against attacks. Use both layers. Client-side is for UX. Server-side is for security.
What is the difference between escaping and sanitization?
Escaping converts dangerous characters so they are treated as plain text (for example, turning < into <). Sanitization removes dangerous content entirely (for example, stripping out all HTML tags). Escaping keeps the data; sanitization removes the threat. For most form data, sanitization (removing tags entirely) is safer than escaping (converting them).
Do I need to worry about injection attacks on read-only forms?
If a form only displays information (does not submit anything), it has no injection vulnerability. However, if that form ever displays user-submitted data, you still need to sanitize. An attacker could have submitted malicious code before, and when you display it, that code runs. Always sanitize any user-submitted data before displaying it, regardless of the form type.

Put it to work
on your own website.

Start free with WEMASY and build your site in a few minutes.