Transform inputs

You've probably entered your phone number or bank details into a form and, like magic, it was converted into a more readable format. Learn how that works with Modular Forms in this guide.

Input transformation works only if your fields are controlled. Make sure you have read the guide about controlled fields beforehand.

The transform prop

The goal of input transformation is to change the user's input at a given time. Typically at the change or blur event. This is made possible with the transform property of the Field component.

As with the validate property, you can pass a single function or multiple functions in an array. You can use our toCustom function or write your own functions based on it. More on that in a moment.

<Field
  name="phone"
  transform={toCustom(
    (value, event) => {
      // Transform phone number here
    },
    { on: 'change' }
  )}
>
  {(field, props) => (
    <input
      {...props}
      type="tel"
      placeholder="(000) 000-0000"
      value={field.value.value || ''}
    />
  )}
</Field>

How toCustom works

The first parameter of the toCustom function is executed if the current event type is the event type you specified in the second parameter. The function gives you access to the current value, as well as to the event object, which you can use to access the reference of the <input /> element via event.target if needed.

String transformation

Besides toCustom, Modular Forms also provide toTrimmed, toLowerCase and toUpperCase by default to transform strings. If you have ideas for other useful transformation functions, let us know with an issue on GitHub.

Create custom functions

To make your code reusable and more readable, you can create your own transformation functions based on toCustom. As promised, we show how this works, using a phone number transformation as an example.

Phone number transformation

A US phone number starts with 3 numbers, surrounded by round brackets, which gives information about the area. Then, after a space, 7 more numbers follow, with a hyphen between the first three and the last four.

import { toCustom, TransformOptions } from '@modular-forms/react';

export function toPhoneNumber(options: TransformOptions) {
  return toCustom<string>((value) => {
    // Remove everything that is not a number
    const numbers = value.replace(/\D/g, '');

    // Continue if string is not empty
    if (numbers) {
      // Extract area, first 3 and last 4
      const [, area, first3, last4] = numbers.match(
        /(\d{0,3})(\d{0,3})(\d{0,4})/
      );

      // If length or first 3 is less than 1
      if (first3.length < 1) {
        return `(${area}`;
      }

      // If length or last 4 is less than 1
      if (last4.length < 1) {
        return `(${area}) ${first3}`;
      }

      // Otherwise return full US number
      return `(${area}) ${first3}-${last4}`;
    }

    // Otherwise return an emty string
    return '';
  }, options);
}

Use custom function in JSX

You can now call the toPhoneNumber transformation function and pass it to the transform property as follows:

<Field name="phone" transform={toPhoneNumber({ on: 'change' })}>
  {(field, props) => (
    <input
      {...props}
      type="tel"
      placeholder="(000) 000-0000"
      value={field.value.value || ''}
    />
  )}
</Field>

Advanced usage

Together with controlled fields, the transformation API can also be used to hold values internally in a different format than they are externally accessible. A practical example is the handling of monetary amounts.

Monetary amounts

In many cases, monetary amounts are stored in the database as integers and thus in cents. However, as an end user, we expect a decimal number in € or $. To save the effort of converting the numbers to € or $ after retrieving them from the database and converting them back to cents before saving them, the following trick can be used.

Note that this procedure only works if JavaScript is enabled in the browser.

Practical example

Pass the amounts to Modular Forms in cents. Then, before you display them in an <input /> element, convert the amount to € or $. Once an input is made, use the transform property to convert the amount back to cents before Modular Forms updates the state. Below is a code example.

<Field
  name="price"
  type="number"
  transform={toCustom((value) => value && value * 100, {
    on: 'change',
  })}
>
  {(field, props) => {
    const value = useSignal<string | number>('');
    useSignalEffect(() => {
      if (!Number.isNaN(field.value.value)) {
        input.value =
          field.value.value === undefined ? '' : field.value.value / 100;
      }
    });
    return <input {...props} type="number" value={value.value} />;
  }}
</Field>

Make it reusable

If you need this functionality for multiple fields, we recommend wrapping the logic in a PriceInput component and toCents transformation function.

import {
  Maybe,
  MaybeValue,
  toCustom,
  TransformField,
} from '@modular-forms/react';

export function toCents<
  TValue extends MaybeValue<number>
>(): TransformField<TValue> {
  return toCustom<TValue>(
    (value) => value && ((value * 100) as Maybe<TValue>),
    { on: 'change' }
  );
}