Skip to main content

Form

A form is a composition of one or more fields. A form may even contain other nested forms inside it.

constructor(fields)​

Instantiates a new form. fields must be an object which is comprised of Field or FormArray instances.

const form = new Form({
name: Field.text(),
age: Field.number(),
job: new Form({
companyName: Field.text(),
role: Field.text(),
}),
});

Properties​

.fields​

Map of fields that this form is composed of.

const form = new Form({
name: Field.text("John Doe"),
age: Field.number(),
});

console.log(form.fields.name.value); // prints "John Doe"

.validation​

A Validation object representing the field's state of validation. Undefined unless the form has been validated before.

.errors​

Observable list of validation errors of the form's fields, or if there aren't any, its own validation errors.

.error​

Observable, first validation error from the form's fields, or if there aren't any, the first from its own validation errors. Shorthand for form.errors[0].

.fieldErrors​

Observable list of validation errors from the form's fields.

.fieldError​

Observable first validation error from the form's fields. Shorthand for form.fieldErrors[0].

.formErrors​

Observable list of validation errors from the form itself. Shorthand for form.validation.errors.

.formError​

Observable validation error from the form itself. Shorthand for form.formErrors[0].

Methods​

.snapshot()​

Recursively snapshots the current state of the form and returns it as a plain JavaScript object.

const form = new Form({
name: Field.text("John Doe"),
hobbies: new FormArray([
new Form({ description: Field.text("photography") }),
new Form({ description: Field.text() }),
]),
});

console.log(form.snapshot());
// prints { name: "John Doe", hobbies: [{ description: "photography" }, {}] }

.reset()​

Recursively resets each field and removes the validation state.

const form = new Form({
name: Field.text("John Doe"),
});
form.fields.name.set("Johnny Doe");
form.reset();

console.log(form.snapshot());
// prints { name: "John Doe" };

.validate()​

Triggers validation using the form's snapshot. All fields are validated as well.

Returns a promise for the finished validation state.

const form = new Form({ name: Field.text() });
const validation = await form.validate();
if (validation.state === "valid") {
console.log("The form and all its fields are valid");
}

.addValidators(...validators)​

Adds one or more validators.
A validator is either a function, or an object with a validate function. It takes a snapshot of the form and throws an error, or returns a promise that rejects, if the value is invalid.

function isAnswer({ number1, number2 }: { number1: number; number2: number }) {
if (number1 + number2 !== 42) {
throw new Error("Not the right answer");
}
}

const answer = new Form({
number1: Field.number(),
number2: Field.number(),
});
await answer.addValidators(isAnswer).validate();
console.log(answer.error); // "Not the right answer"