inputs-sanitize
v1.1.1
Published
Lightweight utility to sanitize and filter input strings for React, Vue and other frameworks
Downloads
428
Maintainers
Readme
inputs-sanitize 🛡️
A lightweight, zero-dependency utility to sanitize and filter input strings. Perfect for React, Vue, Angular, Svelte and other JavaScript/TypeScript frameworks.
Supports both CommonJS and ES Modules (ESM) for maximum compatibility with npm, yarn, and pnpm.
Features
- ✅ Multiple sanitization modes (text, numbers, alphanumeric, safe, custom)
- ✅ Custom regex support - Define your own sanitization patterns
- ✅ TypeScript support with full type definitions
- ✅ Framework agnostic - works with React, Vue, Angular, Svelte, etc.
- ✅ Dual module support - CommonJS & ESM
- ✅ Zero dependencies
- ✅ Small bundle size (~1KB minified)
Installation
# using npm
npm install inputs-sanitize
# using yarn
yarn add inputs-sanitize
# using pnpm
pnpm add inputs-sanitizeAPI
sanitize(value: string, mode?: SanitizeMode, options?: NumberOptions): string
Sanitizes input strings based on the specified mode.
SanitizeMode Types
"text" - Letras con acentos, espacios, puntos, comas y guiones
- ✓ Permite:
a-z,A-Z,áéíóúÁÉÍÓÚñÑ, espacios,.,,,-,_ - ✗ Elimina: números, caracteres especiales
- Uso: Nombres, direcciones, descripciones
- Ejemplo:
"José María, México."→"José María, México."
"numbers" - Solo números con soporte decimal y negativo opcional
- ✓ Permite:
0-9,.(decimal siallowDecimal=true),-(negativo siallowNegative=true) - ✗ Elimina: letras, caracteres especiales
- Opciones:
allowDecimal(default: true),allowNegative(default: true) - Uso: Precios, cantidades, edades, códigos numéricos
- Ejemplo:
"$99.99"→"99.99""-42.5"(con opciones) →"-42.5""-42.5"(sin negativos) →"42.5"
"alphanumeric" - Combinación de TEXT + NUMBERS
- ✓ Permite:
a-z,A-Z,áéíóúÁÉÍÓÚñÑ,0-9, espacios,.,,,-,_ - ✗ Elimina: caracteres especiales (@ ! # $ % etc.)
- Uso: Direcciones con números, nombres con códigos, descripciones con valores
- Ejemplo:
"Calle 123, Apto 45, México."→"Calle 123, Apto 45, México."
"safe" - Solo letras, números y espacios (sin acentos)
- ✓ Permite:
a-z,A-Z,0-9, espacios - ✗ Elimina: acentos, puntos, comas, caracteres especiales
- Uso: Usernames, códigos, referencias
- Ejemplo:
"josé_user@123"→"jos user123"
"all" - Sin cambios (valor por defecto)
- ✓ Permite: Todo
- Uso: Cuando no necesitas filtrado
- Ejemplo:
"José: $123.45!"→"José: $123.45!"
"custom" - Utiliza un regex personalizado
- ✓ Permite: Lo que especifiques en
customRegex - ✓ Requiere: Opción
customRegex: RegExp - Opciones:
customRegex(required) - Uso: Filtrado personalizado según tus necesidades
- Ejemplo:
sanitize('Test@Email#123', 'custom', { customRegex: /[^a-zA-Z0-9]/g })→"TestEmail123" - Nota: Ideal para casos específicos que no cubre ningún modo predefinido
SanitizeOptions
interface SanitizeOptions extends NumberOptions {
customRegex?: RegExp;
}
interface NumberOptions {
allowDecimal?: boolean; // default: true
allowNegative?: boolean; // default: true
}Estas opciones son opcionales según el modo:
allowDecimal(solo"numbers"): Permite caracteres de punto (.) para números decimalestrue(default):"99.99"es válidofalse:"99.99"→"9999"
allowNegative(solo"numbers"): Permite caracteres de guion (-) para números negativostrue(default):"-42"es válidofalse:"-42"→"42"
customRegex(solo"custom"): RegExp personalizado que especifica qué caracteres eliminar- Requerido cuando usas
mode: "custom" - El regex define el patrón a remover del input
- Ejemplo:
/[^a-zA-Z0-9]/gelimina todo excepto letras y números
- Requerido cuando usas
Input Type Handling
La función maneja automáticamente diferentes tipos de entrada:
| Input | Tipo | Comportamiento |
|-------|------|----------------|
| "José María" | string | ✅ Se sanitiza normalmente |
| 123 | number | ✅ Se convierte a string |
| null | null | ✅ Devuelve "" (vacío) |
| undefined | undefined | ✅ Devuelve "" (vacío) |
| [1, 2, 3] | array | ✅ Rechaza, devuelve "" |
| {name: 'José'} | object | ✅ Rechaza, devuelve "" |
| () => {} | function | ✅ Rechaza, devuelve "" |
Notas importantes:
- ✅ Solo acepta
stringynumbercomo valores válidos - ✅ Conserva espacios al inicio/final mientras sanitiza caracteres según el modo
- ✅ Rechaza objetos, arrays y funciones (devuelve vacío en lugar de error)
- ✅ Nunca lanza excepciones
Usage Examples
React
import { sanitize } from 'inputs-sanitize';
import { useState } from 'react';
export default function MyComponent() {
const [email, setEmail] = useState('');
const [username, setUsername] = useState('');
const handleEmailChange = (e) => {
const sanitized = sanitize(e.target.value, 'safe');
setEmail(sanitized);
};
const handleUsernameChange = (e) => {
const sanitized = sanitize(e.target.value, 'alphanumeric');
setUsername(sanitized);
};
return (
<div>
<input
type="email"
value={email}
onChange={handleEmailChange}
placeholder="Email"
/>
<input
type="text"
value={username}
onChange={handleUsernameChange}
placeholder="Username"
/>
</div>
);
}Vue 3
<template>
<div>
<input
v-model="email"
@input="email = sanitize($event.target.value, 'safe')"
type="email"
placeholder="Email"
/>
<input
v-model="amount"
@input="amount = sanitize($event.target.value, 'numbers', { allowDecimal: true })"
type="number"
placeholder="Amount"
/>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { sanitize } from 'inputs-sanitize';
const email = ref('');
const amount = ref('');
</script>Vue 2
<template>
<div>
<input
v-model="name"
@input="handleNameChange"
type="text"
placeholder="Full Name"
/>
<input
v-model="phone"
@input="handlePhoneChange"
type="tel"
placeholder="Phone (numbers only)"
/>
</div>
</template>
<script>
import { sanitize } from 'inputs-sanitize';
export default {
data() {
return {
name: '',
phone: ''
};
},
methods: {
handleNameChange() {
this.name = sanitize(this.name, 'text');
},
handlePhoneChange() {
this.phone = sanitize(this.phone, 'numbers', { allowNegative: false });
}
}
};
</script>Vanilla JavaScript
import { sanitize } from 'inputs-sanitize';
// CommonJS
// const { sanitize } = require('inputs-sanitize');
const input = document.getElementById('myInput');
input.addEventListener('input', (e) => {
e.target.value = sanitize(e.target.value, 'alphanumeric');
});Examples by Mode
Text Mode
import { sanitize } from 'inputs-sanitize';
// Permitir: letras (acentos), espacios, puntos, comas, guiones
// Eliminar: números, caracteres especiales
sanitize('José María, México 123!', 'text');
// → "José María, México "
sanitize('Dr. Juan Pérez, Médico.', 'text');
// → "Dr. Juan Pérez, Médico."
sanitize('María-José García_López', 'text');
// → "María-José García_López"Numbers Mode
// Permitir: números, decimales (opcional), negativos (opcional)
// Eliminar: letras, caracteres especiales
// Con decimales y negativos (default)
sanitize('Price: $99.99', 'numbers');
// → "99.99"
sanitize('Temperature: -15.5°C', 'numbers');
// → "-15.5"
// Sin decimales
sanitize('$99.99', 'numbers', { allowDecimal: false });
// → "9999"
// Sin negativos
sanitize('-42.5', 'numbers', { allowNegative: false });
// → "42.5"
// Sin ambos
sanitize('-$99.99', 'numbers', { allowDecimal: false, allowNegative: false });
// → "9999"Alphanumeric Mode
// Permitir: letras (acentos), números, espacios, puntos, comas, guiones
// Eliminar: caracteres especiales (@!#$%^&*)
sanitize('Calle Principal 123, Apto 4A.', 'alphanumeric');
// → "Calle Principal 123, Apto 4A."
sanitize('José María: $123.45 @user!', 'alphanumeric');
// → "José María 123.45 user"
sanitize('Order #12345, Amount: $99.99, Client: María-José', 'alphanumeric');
// → "Order 12345, Amount 99.99, Client María-José"
sanitize('user_name-123', 'alphanumeric');
// → "user_name-123"Safe Mode
// Permitir: letras (sin acentos), números, espacios
// Eliminar: acentos, puntos, comas, caracteres especiales
sanitize('<script>alert("xss")</script>', 'safe');
// → "scriptalertxssscript"
sanitize('[email protected]', 'safe');
// → "useremailcom"
sanitize('José_123@domain', 'safe');
// → "Jos 123domain"All Mode
// Permitir: todo (sin cambios)
sanitize('José María: $123.45 @user!', 'all');
// → "José María: $123.45 @user!"
sanitize('<script>dangerous</script>', 'all');
// → "<script>dangerous</script>"Custom Mode
// Permitir: lo que especifiques en el regex
// Eliminar: todo lo que NO coincida con el patrón
// Permitir solo letras y números
sanitize('Test@Email#123!', 'custom', { customRegex: /[^a-zA-Z0-9]/g });
// → "TestEmail123"
// Permitir solo dígitos (extrae números)
sanitize('Código: ABC-123-XYZ', 'custom', { customRegex: /[^0-9]/g });
// → "123"
// Permitir letras, números y guiones
sanitize('user@name-123#test', 'custom', { customRegex: /[^a-zA-Z0-9\-]/g });
// → "user name-123test"
// Personalizado: permitir dominios de email
sanitize('[email protected]!', 'custom', { customRegex: /[^a-zA-Z0-9@.\-_]/g });
// → "[email protected]"Comparison Table
Character Support by Mode
| Carácter | text | numbers | alphanumeric | safe | all | custom | |----------|------|---------|--------------|------|-----|--------| | Letras (a-z, A-Z) | ✓ | ✗ | ✓ | ✓ | ✓ | * | | Acentuadas (á, é, í, ó, ú, ñ) | ✓ | ✗ | ✓ | ✗ | ✓ | * | | Números (0-9) | ✗ | ✓ | ✓ | ✓ | ✓ | * | | Punto (.) | ✓ | ✓* | ✓ | ✗ | ✓ | * | | Coma (,) | ✓ | ✗ | ✓ | ✗ | ✓ | * | | Guion medio (-) | ✓ | ✓* | ✓ | ✗ | ✓ | * | | Guion bajo (_) | ✓ | ✗ | ✓ | ✗ | ✓ | * | | Espacio | ✓ | ✗ | ✓ | ✓ | ✓ | * | | Especiales (@!#$%^&*) | ✗ | ✗ | ✗ | ✗ | ✓ | * |
*numbers mode: punto (.) = decimal si allowDecimal=true, guion (-) = negativo si allowNegative=true
*custom mode: depende del patrón regex que especifiques en customRegex
Framework Integration
TypeScript with React
import { sanitize, SanitizeMode } from 'inputs-sanitize';
import { ChangeEvent, useState } from 'react';
interface FormData {
username: string;
amount: string;
description: string;
}
export function MyForm() {
const [data, setData] = useState<FormData>({
username: '',
amount: '',
description: ''
});
const handleChange = (
e: ChangeEvent<HTMLInputElement>,
mode: SanitizeMode
) => {
const { name, value } = e.target;
setData(prev => ({
...prev,
[name]: sanitize(value, mode)
}));
};
return (
<form>
<input
name="username"
value={data.username}
onChange={(e) => handleChange(e, 'alphanumeric')}
placeholder="Username"
/>
<input
name="amount"
value={data.amount}
onChange={(e) => handleChange(e, 'numbers')}
placeholder="Amount"
/>
<textarea
name="description"
value={data.description}
onChange={(e) =>
setData(prev => ({
...prev,
description: sanitize(e.target.value, 'safe')
}))
}
placeholder="Description"
/>
</form>
);
}Package Compatibility
| Package Manager | Support | |-----------------|---------| | npm | ✅ Yes | | yarn | ✅ Yes | | pnpm | ✅ Yes | | Node.js | ✅ 14+ | | Browser ES2020+ | ✅ Yes |
Module Formats
This package supports both module formats:
- CommonJS (
dist/cjs/index.js) - for Node.js and older build tools - ESM (
dist/esm/index.js) - for modern applications and bundlers
The correct format is automatically selected based on your environment.
License
MIT
