form-sanitize
v1.0.0
Published
Schema-based form sanitization that works on frontend and backend
Maintainers
Readme
form-sanitize
Schema-based form sanitization that works on your React frontend and Express backend — define rules once, run everywhere.
Why form-sanitize?
| | DOMPurify | validator.js | form-sanitize | |---|---|---|---| | Works in Node.js | ❌ | ✅ | ✅ | | Schema-based | ❌ | ❌ | ✅ | | Chainable API | ❌ | ❌ | ✅ | | Nested objects | ❌ | ❌ | ✅ | | Zero dependencies | ✅ | ✅ | ✅ |
Install
npm install form-sanitizeQuick start
import { createSchema, s } from 'form-sanitize'
const contactForm = createSchema({
name: s.string().trim().stripTags(),
email: s.string().trim().normalizeEmail(),
age: s.number().clamp(0, 120),
active: s.boolean(),
address: s.object({
city: s.string().trim(),
zip: s.string().truncate(10),
}),
})
const clean = contactForm.sanitize(req.body)API
s.string()
| Method | Description |
|---|---|
| .trim() | Remove leading/trailing whitespace |
| .stripTags() | Remove HTML and script tags including content |
| .truncate(n) | Limit to n characters |
| .normalizeEmail() | Lowercase, remove Gmail dots and aliases |
| .escape() | HTML-encode special characters |
| .toSlug() | Convert to URL-safe slug |
s.number()
| Method | Description |
|---|---|
| .clamp(min, max) | Keep value within range |
| .round(decimals) | Round to decimal places |
| .abs() | Make value positive |
s.boolean()
Coerces "true", "yes", "1", 1 → true and "false", "no", "0", 0 → false.
s.object(definition)
Sanitize nested objects recursively.
License
MIT
