📖 Introduction
React Form Sanitization is a lightweight TypeScript utility package designed to help developers efficiently manage and sanitize form data after submission. This package is specifically crafted to make creating and handling FormData
hassle-free. It offers two key functions—sanitizeFormData
and sanitizeFormValue
—which remove unwanted values from form data, such as undefined
, null
, empty strings, and other falsy values. By streamlining the sanitization process, this library ensures developers can work with clean, validated data structures, making it particularly useful for processing, storage, or API calls in modern applications.
📝 Documentation
You can find more details, and other docs on documentation
📦 Installation
The React Form Sanitization package can be installed using your preferred package manager:
NPM
npm i react-form-sanitization
Yarn
yarn add react-form-sanitization
PNPM
pnpm add react-form-sanitization
Make sure you have Node.js installed on your system before proceeding with the installation. The package is compatible with React applications using version 16.8.0 or higher.
✨ Key Features
- Data Sanitization: Removes
undefined
, null
, empty strings, and other falsy values from form data to ensure a clean output. - Flexible Filtering: Provides
ignoreKeys
, requiredKeys
, preservePaths
, and trimStrings
parameters for custom control over sanitization, allowing specific fields or paths to be excluded, retained, or trimmed. - TypeScript Support: Built with TypeScript, ensuring type safety and seamless integration with TypeScript-based projects.
- Minimal Impact: Small bundle size with minimal performance overhead, making it suitable for production environments.
- File Upload Support: Handles image and file uploads efficiently by automatically detecting and preserving File/Blob objects when creating FormData, making it ideal for multipart/form-data submissions.
- FormData Creation: Seamlessly converts complex JavaScript objects into FormData instances while maintaining proper file handling and nested object structures.
⌨️ Functions
1. sanitizeFormData
This function is specially designed for creating `FormData by removing unwanted values from the entire form data object. It accepts customizable options such as excluding specific keys or retaining required fields.
Parameters
formData
: The form data object to sanitize.options
(Optional):
ignoreKeys
(string[]): Array of field names that should not be sanitized or removed.requiredKeys
(string[]): Array of field names that are required and should not be removed, even if their values are falsy (undefined
, null
, or ""
).lowerCaseKeys
(string[]): Arrray of keys to convert to lowercase.preservePaths
(string[]): Array of string paths to ensure nested or complex object properties are retained during sanitization.trimStrings
(boolean): Indicates whether string values should be trimmed.
Example
import React from "react";
import { sanitizeFormData } from "react-form-sanitization";
import { useUpdateProfileMutation } from "../api";
const Profile = () => {
const [updateProfile] = useUpdateProfileMutation();
const handleSubmit = async (values) => {
const cleanedData = sanitizeFormData(
{
...values,
active: false,
remember: true,
info: [
{ address: "123 Main St", city: "New York" },
{ address: "", city: "Los Angeles" },
{ address: "789 Pine Rd", city: "Chicago" },
],
},
{
requiredKeys: ["active"],
ignoreKeys: ["remember"],
preservePaths: ["info[*].address"],
}
);
await updateProfile(cleanedData);
};
return <Form onSubmit={handleSubmit}>...</Form>;
};
2. sanitizeFormValue
This function sanitizes individual form values with customizable settings for excluding or requiring fields. It works similarly to sanitizeFormData
but is tailored for individual value sanitization.
Parameters
formValue
: The value to sanitize.options
(Optional):
ignoreKeys
(string[]): Array of field names that should not be sanitized or removed.requiredKeys
(string[]): Array of field names that are required and should not be removed, even if their values are falsy (undefined
, null
, or ""
).lowerCaseKeys
(string[]): Arrray of keys to convert to lowercase.preservePaths
(string[]): Array of string paths to ensure nested or complex object properties are retained during sanitization.trimStrings
(boolean): Indicates whether string values should be trimmed.
Example
import React from "react";
import { sanitizeFormValue } from "react-form-sanitization";
import { useUpdateProfileMutation } from "../api";
const Profile = () => {
const [updateProfile] = useUpdateProfileMutation();
const handleSubmit = async (values) => {
const cleanedData = sanitizeFormValue(
{
...values,
username: "john_doe",
info: {
name: "John Doe",
email: "john@example.com",
address: {
street: "123 Main St",
city: "",
state: "CA",
},
},
},
{
ignoreKeys: ["username"],
preservePaths: ["info.address.city"],
}
);
await updateProfile(cleanedData);
};
return <Form onSubmit={handleSubmit}>...</Form>;
};
📡 Usage with CDN
To use React Form Sanitization without installing it via a package manager, you can include the necessary CDNs for React, ReactDOM, and React Form Sanitization directly in your HTML file.
<script
crossorigin
src="https://unpkg.com/react@17/umd/react.production.min.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"
></script>
<script src="https://cdn.jsdelivr.net/npm/react-form-sanitization@6.0.6/dist/index.umd.js"></script>
Example
<script>
document.addEventListener("DOMContentLoaded", () => {
const { sanitizeFormValue } = window.ReactFormSanitization;
const formValues = {
name: " John Doe ",
email: "john@example.com",
address: null,
phone: undefined,
city: "New York",
};
const sanitizedData = sanitizeFormValue(formValues, {
requiredKeys: ["name", "email"],
trimStrings: true,
});
console.log(sanitizedData);
});
</script>
🗂️ API Documentation
sanitizeFormData(formData, options)
- Parameters:
formData
: An object representing the form data.options
: An optional object containing:
ignoreKeys
: Array of keys to ignore during sanitization.requiredKeys
: Array of keys that are required, even if they have falsy values.preservePaths
: Array of paths to ensure nested properties are retained.lowerCaseKeys
: Arrray of keys to convert to lowercase.trimStrings
: Boolean to indicate whether to trim string values.
- Returns: A new object with sanitized values.
sanitizeFormValue(formValue, options)
- Parameters:
formValue
: A single form value.options
: Same as sanitizeFormData
.
- Returns: A sanitized value, which may be null, undefined, or cleaned based on the given conditions.
Input Parameters and Configuration Options
Option | Type | Description |
---|
ignoreKeys | string[] | Array of keys to exclude from sanitization. These fields will remain untouched. |
requiredKeys | string[] | Array of keys that are required, even if their values are falsy (undefined , null , or "" ). |
preservePaths | string[] | Array of paths to ensure nested or complex object properties are retained during sanitization. Use cases include: [*] to preserve all items in an array, ['name.key'] to retain specific nested keys, ['name[*].key'] to preserve a key within each object in an array, and ['name[2].name'] to retain a specific key at a specific index in an array. This ensures important data in nested or complex structures is not removed unintentionally. |
lowerCaseKeys | string[] | Array of keys whose string values should be converted to lowercase during sanitization. |
trimStrings | boolean | If true , string values will be trimmed (leading and trailing whitespace removed). Defaults to true . |
Available Patterns for preservePaths
Pattern | Description | Example |
---|
[*] | Matches all items in an array. | address[*] will preserve all objects in the address array. |
['key.subKey'] | Matches a specific nested key path. | user.profile will preserve the profile field under the user object. |
['key[*].subKey'] | Matches a specific key within each object in an array. | address[*].city will preserve the city field for all objects in the address array. |
['key[index].subKey'] | Matches a specific index within an array and preserves the key at that specific index. | address[2].city will preserve the city field for the object at index 2 in the address array. |
['key'] | Matches a specific top-level key and ensures it is retained. | photo will preserve the photo field at the top level of the object. |
['key[*]'] | Matches all elements in an array under a specific key. | items[*] will preserve all elements of the items array. |
| | |
📝 Summary
React Form Sanitization provides a simple, effective solution for managing form data cleanliness in TypeScript projects. By offering robust data sanitization and flexible filtering options, this package ensures form submissions are optimized for further processing, storage, or API calls. With its small footprint and TypeScript support, it's an essential tool for maintaining high-quality, validated form data in modern React applications.
📜 License
Licensed under MIT