Back to cheatsheets
Developer
Input Validation Patterns
Server-side validation patterns for common input types using allowlist regex.
What you'll learn
- Allowlist validation
- Length and range checks
How to use these snippets
- Click the Copy button next to any snippet to copy it to your clipboard.
- Paste the code into your project, IDE, or terminal.
- Replace placeholder values (like
example.comoryour-secret) with your actual data. - Review the code comments for important security notes and caveats.
Code Snippets
Copy-paste code snippets
2 ready-to-use snippets for input validation patterns. Click copy and paste into your project.
Allowlist validation
function validateInput(input, type) {
const patterns = {
email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
domain: /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/,
hash: /^[0-9a-f]{64}$/i,
url: /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/,
ip: /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.){3}(25[0-5]|(2[0-4]|1\d|[1-9]|)\d)$/,
};
return patterns[type]?.test(input) ?? false;
}
Length and range checks
function validateRange(value, opts) {
const { min, max, type } = opts;
if (type === 'string') {
if (value.length < min || value.length > max)
return false;
} else if (type === 'number') {
if (value < min || value > max)
return false;
if (!Number.isFinite(value))
return false;
}
return true;
}
// Sanitize HTML output
function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
100% Free · No signup · No cost
Generate something unguessable right now
148 bits of entropy, a crack-time estimate you can trust, and a clipboard that clears itself after 30 seconds.
Part of the Toolly ecosystem · secure.toolly.site