Kin Form
Docs
INTRODUCTION
Getting Started Architecture

EXAMPLES
Basic Example Any-level Validation Dependent Field Validation Flexible Form Structures Flexible Field Components Array

API

Any-level Validation

This example demonstrates validation at three levels (leaf field, field group, and whole form).

Key Concepts

Kin Form allows you to apply validation logic at any level of your form's structure, from individual fields to nested groups to the entire form itself. This example shows how to add validators at three different levels.

  1. Leaf Field Validation: The most common type of validation. The text-field for "Line 1" has a required validator attached directly to it via the .validators property. This validator runs whenever the field's value changes.

    // Validator for the individual field
    const leafFieldValidators = [required("[Leaf level] Line 1 is required")];
    
    // Applied in the template
    html`<text-field .validators=${leafFieldValidators}></text-field>`
    
  2. Field Group Validation: The <kin-field-group> that wraps the address fields also has its own .validators property. This allows you to perform validation that depends on multiple fields within the group. The validator function receives the FieldGroup instance as an argument, so it can inspect the entire value of the group.

    // Validator for the group
    const groupValidators = [
      (field: KinFieldGroup<Address>) =>
        field.value.line1 ? null : "[Group level] Line 1 is required",
    ];
    
    // Applied in the template
    html`<kin-field-group .validators=${groupValidators}></kin-field-group>`
    
  3. Form-level Validation: Finally, you can pass a validators function to the FormController constructor. This is for top-level validation that might depend on the entire form's data. The function receives the FormController instance and can access the complete form value.

    // Validator for the whole form
    const form = new FormController<Model>(this, {
      // ...
      validators: (form) => {
        return form.value.billingAddress.line1
          ? null
          : "[Form level] Line 1 is required";
      },
    });
    

By combining these different levels, you can implement complex validation logic in a clean, hierarchical, and maintainable way.

Live Demo

On this page

Key Concepts Live Demo
Created with ♥️ by  Man Hoang (Kin)