Documentation

class FormState

An object that contains form field data, with validation rules.

class FormState<
TSchema extends Record<string, unknown> = Record<string, unknown>,
> extends ObservableObject;

Description

The FormState class provides a data model for user input, allowing UI elements to read and write data from/to a single form state object — instead of having to use individual bindings and event handlers for each field.

The form state object provides methods to get, set, and clear field values, as well as a way to validate current values according to a schema or custom validation functions. Form values and validation errors can be bound to any other view properties to be displayed in the UI.

Validation is performed using a Schema instance. Errors must be added as strings or StringConvertible values (e.g. the result of fmt()) using the required() or error() methods of each field in the schema.

The validation mode determines when fields are validated — see FormState.ValidationMode and FormState.setValidation().

To use a FormState object with UITextField or UIToggle input elements, use their .formStateValue() builder method.

Examples

function FormView(v: Binding<MyActivity>) {
  return UI.Column(
    UI.TextField().formStateValue(v.bind("form"), "foo"),
    UI.Text(v.bind("form.errors.foo.message"))
      .hideWhen(v.bind("form.errors.foo").not()),
    UI.Button("Go").onClick("Submit")
  );
}

class MyActivity extends Activity {
  static View = FormView;

  form = new FormState((f) => f.object({
    foo: f.string().required("Foo is required")
  }));

  onSubmit() {
    let values = this.form.validate();
    // now, values.foo is a string with length > 0,
    // OR otherwise
    // - values is undefined, and
    // - this.form.valid is false, and
    // - this.form.errors.foo is "Foo is required"
  }
}

Constructor

Type members

Instance members

Inherited members