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.
-
Leaf Field Validation: The most common type of validation. The
text-fieldfor "Line 1" has arequiredvalidator attached directly to it via the.validatorsproperty. 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>` -
Field Group Validation: The
<kin-field-group>that wraps the address fields also has its own.validatorsproperty. This allows you to perform validation that depends on multiple fields within the group. The validator function receives theFieldGroupinstance as an argument, so it can inspect the entirevalueof 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>` -
Form-level Validation: Finally, you can pass a
validatorsfunction to theFormControllerconstructor. This is for top-level validation that might depend on the entire form's data. The function receives theFormControllerinstance 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.