npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

react-form-sanitization

v6.0.10

Published

A React package for sanitizing form data and values to ensure clean input and prevent injection attacks.

Downloads

192

Readme

📖 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"], // This field will be retained even if its value is falsy
        ignoreKeys: ["remember"], // This field will be removed even if its value is truthy
        preservePaths: ["info[*].address"], // This info all address will be retained even if its value is falsy
      }
    );
    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: "[email protected]",
          address: {
            street: "123 Main St",
            city: "",
            state: "CA",
          },
        },
      },
      {
        ignoreKeys: ["username"], // This field will be removed even if its value is truthy
        preservePaths: ["info.address.city"], // This path will be retained even if its value is falsy
      }
    );
    await updateProfile(cleanedData);
  };

  return <Form onSubmit={handleSubmit}>...</Form>;
};

🗂️ 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