Guide

Install

You can install @websublime/forms via npm or yarn using the following command:

npm @websublime/forms --save
# or
yarn add @websublime/forms

Note

@websublime/forms has as unique dependency @websublime/schema

Usage

import { NumberType } from '@websublime/schema';
import { FormControl } from '@websublime/forms';

const schema = NumberType()
  .isRequired()
  .max(10);

const control = new FormControl(schema);

control.setData(11);

expect(control.isValid).toBeTruthy();
expect(control.hasErrors).toBeFalsy();

await control.validate();

expect(control.isValid).toBeFalsy();
expect(control.hasErrors).toBeTruthy();

console.log(control.errors[0].i18n); // ERRORS.NUMBER.MAX
console.log(control.errors[0].constraints); // { max: 10 }
console.log(control.errors[0].value); // 11

BaseControl

Forms has three type of object models, all of them extends BaseControl:

If we have a model like this, we will get the following form model mapping

class Car {
  // --> FormGroup for Car
  model: string; // --> FormControl model
  extras: string[]; // --> FormArray of FormControls for extras
  motor: {
    // FormGroup for Motor
    type: string; // FormControl type
    shift: number; // FormControl shift
  };
}

All forms object model have a internal state:

  • isDirty - A control is dirty if the user has changed the value in the UI.
  • isTouch - A control is marked touched once the user has triggered a blur event on it.
  • isFocus - A control is marked focus once the user has triggered a focus eventon it. And set to false when a blur event happens.
  • isPrestine - A control is pristine if the user has not yet changed the value in the UI.
  • isLoading - A control is executing validations.
  • isValid - A control is valid.
  • errors: An array of errors generated by failing validation. The order the validation are executed is the order the error are in the array.
  • context: key if the control belongs to a FormGroup or index if the control belogin to an FormArray.
  • items: Only present in the FormArray. Is an array of controls.
  • properties: Only present in the `FormGroup. Is a record for controls.
  • schema: Validation Schema.
  • parent: Parent control.