Skip to content
forms

Rules

Disable or hide a field based on the rest of the form.

Some fields depend on others: no street when the order is picked up, no gift message unless it is a gift. rules() sets fields disabled or hidden from the rest of the value, in the same render as the change.

Put rules() in the form’s plugins, and a ruled(...) part after the definition’s config. ruled takes a map from a field’s dotted name, the same name a name prop takes, to a rule. Each rule gets the form value and returns the field’s disabled and hidden flags. A flag the rule leaves out stays as it is.

const forms = createForms({ plugins: [rules()], fields });

const order = forms.define(
  { defaultValues: { pickup: false, gift: false, street: "", message: "" } },
  ruled({
    street: (value) => ({ disabled: value.pickup }),
    message: (value) => ({ hidden: !value.gift }),
  }),
);

ruled takes its value type from the definition, so value is typed and a name that isn’t a field, such as "stret", is a type error. A form without rules() in its plugins is a type error too.

Rules run when the part attaches and after every batch that writes a value, before listeners, so the flags change in the same render as the value. Disabling an object, such as address, disables every field below it.

Names go through objects only, so a rule can’t name an array item. Give the array a rule, or the object around it.

Rules on a fieldset

A fieldset can carry its own rules. See Parts on fieldsets.

Disabled and hidden

disabled is a field flag, and inputProps(field) puts it on the input. hidden is the plugin’s own meta, so your component reads it and decides what hiding means:

function TextField({ field, label }: TextFieldProps) {
  if (rules.meta(field).hidden) return null;
  // ...
}

A field no rule hides reads { hidden: false }, so the reader never returns undefined.

Server rendering

What the rules set before the store has listeners is part of its starting state. A field a rule disables or hides renders that way on the server and hydrates with no second render.

Last updated