ForgeForm

Sanitizers

ForgeForm goes beyond just validation; it also incorporates data sanitization to ensure the data you collect is clean, consistent, and in the desired format before it's processed or stored. Sanitization automatically modifies user input based on rules you define in your schema, streamlining data handling and reducing the need for manual pre-processing.

Contents

ForgeForm offers built-in sanitization for several field types, particularly focusing on string and date-only types.

1. String Sanitization:

ForgeForm provides sanitization options for string type fields to handle common text formatting needs:

  • Whitespace Trimming: Automatically removes leading and trailing whitespace from string inputs. This ensures that extra spaces accidentally entered by users don't clutter your data.

    • Attribute: trim: boolean

      • true (default): Enables whitespace trimming.
      • false: Disables whitespace trimming.
    • Example:

      import { createSchema } from 'forgeform';
       
      interface TrimFormData {
        username?: string;
        untrimmedInput?: string;
      }
       
      const trimSchema = createSchema<TrimFormData>({
        fields: {
          username: { type: 'string', required: true, trim: true, requiredErrorMessage: 'Username is required' }, // Whitespace will be trimmed (default)
          untrimmedInput: { type: 'string', trim: false }, // Whitespace trimming is disabled
        },
      });

      In this example, if a user enters " John Doe " for username, it will be sanitized to "John Doe". For untrimmedInput, whitespace will be preserved.

  • Case Conversion: Automatically converts string inputs to either lowercase or uppercase. This is useful for standardizing text data where case sensitivity is not important, such as emails or usernames.

    • Attributes:

      • lowercase: boolean
        • true: Converts the string to lowercase.
        • false (default): No lowercase conversion.
      • uppercase: boolean
        • true: Converts the string to uppercase.
        • false (default): No uppercase conversion.
    • Example:

      import { createSchema } from 'forgeform';
       
      interface CaseConversionFormData {
        email?: string;
        productCode?: string;
      }
       
      const caseSchema = createSchema<CaseConversionFormData>({
        fields: {
          email: { type: 'email', required: true, lowercase: true, requiredErrorMessage: 'Email is required' }, // Converted to lowercase before validation and in data
          productCode: { type: 'string', uppercase: true }, // Converted to uppercase before validation and in data
        },
      });

      If a user enters "UserEmail@Example.com" for email, it will be sanitized to "useremail@example.com". If they enter "product123" for productCode, it will be sanitized to "PRODUCT123".

2. Date Sanitization (using date-fns):

For date-only type fields, ForgeForm utilizes the powerful date-fns library to provide consistent date formatting and sanitization. By default, date-only fields in ForgeForm are sanitized and formatted into the ISO 8601 date format (YYYY-MM-DD).

  • Default ISO Date Format: When you define a field as type: 'date-only', ForgeForm automatically ensures that the validated date value is converted and stored in the ISO 8601 format. This is an internationally recognized standard format that ensures consistency and simplifies date parsing across different systems.

    • Example:

      import { createSchema } from 'forgeform';
       
      interface DateFormData {
        eventDate?: Date; // Expecting Date object as input
      }
       
      const dateSchema = createSchema<DateFormData>({
        fields: {
          eventDate: { type: 'date-only', required: true, requiredErrorMessage: 'Event date is required' },
        },
      });

      If a user selects or inputs a date, even if the input format varies, ForgeForm will sanitize and store the eventDate value in the formData in ISO format (e.g., "2023-10-27"). The original input might have been a Date object, a different string format, but the sanitized data will consistently be in YYYY-MM-DD string format after successful validation using date-fns.

  • No Custom Date Format Configuration (Currently): At present, ForgeForm's date-only type is configured to strictly sanitize and output dates in the ISO 8601 format. Direct configuration of custom date formats within the schema (e.g., using format strings like "MM/DD/YYYY") is not directly supported through schema attributes. The focus is on providing a standardized, universally compatible date format via ISO 8601 out-of-the-box.

    (Note: Future versions might explore options for custom date formatting if there's sufficient user demand. For now, developers can handle custom formatting on the UI display side using date-fns format functions if needed.)

How Sanitization Works:

Sanitization in ForgeForm happens automatically as part of the validation process. When you call schema.validate(formData), ForgeForm performs the following steps for each field:

  1. Input Value Retrieval: Retrieves the value provided for the field from the formData.
  2. Sanitization Application: If sanitization attributes are defined in the field schema (like trim, lowercase, uppercase for strings or default ISO formatting for date-only), ForgeForm applies these sanitization rules to the input value before validation occurs.
  3. Validation Execution: After sanitization, the (now potentially modified) value is then passed through the validation rules defined for that field (e.g., required, minLength, format, customValidator).
  4. Data Output: If validation is successful, the sanitized value (not necessarily the original input) is what is included in the validated formData result.

Benefits of Sanitization:

  • Data Consistency: Ensures that data adheres to consistent formatting rules, making it easier to process, compare, and store.
  • Reduced Preprocessing: Minimizes the need for manual data cleaning and formatting logic in your application code. ForgeForm handles common sanitization tasks upfront.
  • Improved Data Quality: By removing extraneous whitespace and standardizing case or date formats, sanitization contributes to higher quality and more reliable data.
  • Integration with Validation: Because sanitization is performed before validation, you are validating against the cleaned, standardized data, ensuring that validation rules are applied to the intended data format.

By using ForgeForm's sanitization features, you can streamline your form handling and improve the quality and consistency of the data you collect in your React applications.

On this page