Spanish Total.js
English
Documentation For AI agents
Contents

Forms and validation

How to build a form from components, validate it, show errors, submit it and reset it.

.md GitHub
On this page

A form is a group of components bound to paths under one object, for example form.name and form.email. Each component keeps its own state: whether the user touched it, changed it, and whether its value is valid. This guide builds a form step by step. How to write components in general is explained in Creating components.

A field with validation

A component takes part in validation when it defines self.validate. The function receives the value and runs each time the value changes.

<ui-component name="input" path="form.name" config="label:Name;required:true"></ui-component>
<ui-component name="input" path="form.email" config="label:Email;required:true;email:true"></ui-component>

<script>
COMPONENT('input', 'label:Field', function(self, config) {

  self.make = function() {
    self.html('<label>' + config.label + '</label><input type="text" /><em></em>');
    self.autobind20();
  };

  self.validate = function(value) {
    if (!config.required)
      return true;
    if (!value)
      return 'This field is required';
    if (config.email && !value.isEmail())
      return 'Enter a valid email address';
    return true;
  };

  self.state = function() {
    self.find('em').text(config.touched && config.invalid ? config.invalid : '');
  };

});
</script>

self.autobind20() connects the <input> to the path. When the user writes ann into the email field and leaves it, the model is {"email":"ann"} and the message Enter a valid email address appears.

The result of self.validate sets config.invalid:

ResultMeaningconfig.invalid
true or an empty stringValidfalse
A non-empty stringInvalid, with a messageThe message
Anything elseInvalidtrue

Field state

ValueCSS classSet when
config.touchedui-touchedThe user typed into the field or left it.
config.modifiedui-modifiedThe user changed the value.
config.invalidui-invalidThe value did not pass the validation.
config.disabledui-disabledThe component is disabled.

The library keeps the classes on the <ui-component> element up to date and calls self.state() after each change of the state.

A required empty field is invalid from the moment the page loads. Testing config.touched as in the example above keeps the message hidden until the user has worked with the field.

Checking the form

ERRORS(path, callback) returns the invalid components under a path. It also accepts a jQuery element and searches inside it. COMPONENTS(path) returns the components that match the flags in the path.

<div id="contact">
  <ui-component name="input" path="form.name" config="label:Name;required:true"></ui-component>
  <ui-component name="input" path="form.email" config="label:Email;required:true;email:true"></ui-component>
  <ui-component name="input" path="form.note" config="label:Note"></ui-component>
</div>

<script>
ON('ready', function() {
  ERRORS('form', function(components) {
    for (var component of components)
      console.log(component.path.toString(), '-', component.config.invalid);
  });

  ERRORS($('#contact'), function(components) {
    console.log(components.length);
  });

  console.log(COMPONENTS('form @invalid').length);
  console.log(COMPONENTS('form @valid').length);
  console.log(COMPONENTS('form @required').length);
  console.log(COMPONENTS('form @modified').length);
});
</script>
form.name - This field is required
form.email - This field is required
2
2
1
2
0

COMPONENTS() understands the flags @invalid, @valid, @touched, @modified, @required, @disabled, @enabled, @visible and @hidden. ERRORS('form @visible', callback) skips the fields that are hidden.

Disabling the submit button

Watch the form, keep the result in a path, and let <ui-bind> disable the button:

<ui-bind path="formstate.invalid" config="disabled"><button>Save</button></ui-bind>

<script>
ON('ready', function() {

  var check = function() {
    ERRORS('form', function(components) {
      SET('formstate.invalid', components.length > 0);
    });
  };

  WATCH('form', check);
  check();

});
</script>

The button is disabled while the name is empty and becomes enabled after SET('form.name', 'Ann').

Submitting

Check the errors, send GET('form'), and reset the form after success. The @change flag marks the fields as touched and modified, which reveals their messages when the user submits too early.

function submit() {
  ERRORS('form', function(components) {

    if (components.length) {
      SET('form @change', GET('form'));
      return;
    }

    AJAX('POST /api/contact/', GET('form'), function(response) {
      if (response.success)
        SET('form @reset', {});
    });
  });
}

Resetting and filling the form

CallEffect
SET('form.name @change', value)Sets the value and marks the field as touched and modified.
RESET('form')Clears the touched and modified state and keeps the values.
SET('form @reset', data)Replaces the data and clears the state. Use it to load a record into a form.
SET('form @default', {})Replaces the data, clears the state and applies the default values.

A default value is a JavaScript expression in the default attribute of the component. It is applied at start and by the @default flag whenever the value is empty.

<ui-component name="input" path="form.name" config="label:Name"></ui-component>
<ui-component name="input" path="form.country" config="label:Country" default="'Slovakia'"></ui-component>

<script>
var show = function(label) {
  var c = FIND('.form.name');
  console.log(label, JSON.stringify(GET('form')), c.config.touched, c.config.modified);
};

ON('ready', function() {
  SET('form.name @change', 'Ann');
  show('@change');
  RESET('form');
  show('RESET');
  SET('form @reset', { name: 'Bob', country: 'Austria' });
  show('@reset');
  SET('form @default', {});
  show('@default');
});
</script>
@change {"country":"Slovakia","name":"Ann"} 1 1
RESET {"country":"Slovakia","name":"Ann"} 0 0
@reset {"name":"Bob","country":"Austria"} 0 0
@default {"country":"Slovakia"} 0 0

More flags are described in Flags and path modifiers.

Converting the value

The type key of the configuration converts the text from the <input> when autobind20() writes it to the model. With type:number, typing 42 stores the number 42:

<ui-component name="input" path="form.age" config="label:Age;type:number"></ui-component>

A field that is required on a condition

The required command of <ui-bind> sets config.required on the components inside it. Call self.validate2() from self.configure to validate again when the option changes:

<ui-bind path="form.company" config="required">
  <div><ui-component name="input" path="form.vat" config="label:VAT number"></ui-component></div>
</ui-bind>

<script>
COMPONENT('input', function(self, config) {

  self.make = function() {
    self.html('<input type="text" />');
    self.autobind20();
  };

  self.validate = function(value) {
    return !config.required || !!value;
  };

  self.configure = function(key) {
    if (key === 'required')
      self.validate2();
  };

});
</script>

The empty field is valid at first. After SET('form.company', true) it is required and invalid, and after SET('form.company', false) it is valid again.

Forms inside a plugin

A plugin is a natural home for a form. The fields use ? paths, exports.set('@reset', data) fills the form, and exports.form returns the data and clears the state of the fields.

<ui-plugin path="contact">
  <ui-component name="input" path="?.name" config="label:Name;required:true"></ui-component>
</ui-plugin>

<script>
PLUGIN('contact', function(exports) {

  exports.load = function(data) {
    exports.set('@reset', data);
  };

  exports.save = function() {
    ERRORS(exports.name, function(components) {
      console.log('errors', components.length);
      if (!components.length)
        console.log(JSON.stringify(exports.form));
    });
  };
});
</script>

Calling EXEC('contact/save') on the empty form prints errors 1. After EXEC('contact/load', { name: 'Ann' }) and SET('contact.name @change', 'Anna'), it prints errors 0 and {"name":"Anna"}.

Made in Europe