# Validation

- Page: https://koobiq.io/en/other/validation/overview

## Overview

Form-field controls display errors via [`ErrorStateMatcher`](https://koobiq.io/en/other/validation.md) — a small policy object that decides _when_ to surface a control's existing errors.

### Summary

- The submit button is never disabled
- Invalid character input is reported as it's typed
- Error messages are shown on blur (focus loss)
- Empty required fields don't show errors on blur
- Fields already in error state are validated as user types

### Opening the form

Focus is placed on the first field. Unfilled fields are not highlighted in red by default. An exception is a saved draft with already-visible errors that the user resumes filling.

[**Example: Validation on open** (`validation-on-open`)](https://koobiq.io/examples/validation-on-open.md)

### Required fields

Required fields are not marked as such if most of the fields are required. Optional fields can be labeled with a tag or placeholder like “Optional.” It's even better to explain why filling in this info is helpful to the user.

[**Example: Validation optional label** (`validation-optional-label`)](https://koobiq.io/examples/validation-optional-label.md)

Some fields can go unmarked as optional if their auxiliary purpose is obvious. For example, “Description.”

If most fields in the form are optional, then the few required ones should be marked. You can add a red asterisk after the label or a gray “Required” tag below the field. Don't use multiple methods for indicating required fields in the same form. The asterisk is the `showRequiredMarker` option of the form field, see [Form field](https://koobiq.io/en/components/form-field.md#label).

[**Example: Validation required label** (`validation-required-label`)](https://koobiq.io/examples/validation-required-label.md)

### When to validate for errors

There are three main strategies for validation:

1. While typing
2. On blur (when leaving the field)
3. After submitting the form

#### While typing

Used to check for valid characters. Invalid characters are filtered out during input, and an error tooltip is shown near the text caret. The message disappears when a valid character is entered or the field loses focus.

[**Example: Validation on type** (`validation-on-type`)](https://koobiq.io/examples/validation-on-type.md)

#### On blur

For fields with complex requirements (like IP address or email), they shouldn't enter an error state during typing to avoid distracting the user. Validation is done on blur — the field is marked invalid and an error message appears beneath it.

[**Example: Validation on blur** (`validation-on-blur`)](https://koobiq.io/examples/validation-on-blur.md)

Empty fields are not validated on blur.

Real-time validation works for fields already marked as invalid. If the value is corrected, the error message disappears and the field is restored to normal state.

Invalid fields remain styled as such if the user leaves the field without correcting the error.

[**Example: Validation on blur filled** (`validation-on-blur-filled`)](https://koobiq.io/examples/validation-on-blur-filled.md)

#### On form submission

By default, errors are shown only for **invalid** (incorrectly filled) fields after the user interacts with them.
To display errors immediately after form submission, use `ShowOnFormSubmitErrorStateMatcher` — an implementation of [ErrorStateMatcher](https://github.com/koobiq/angular-components/blob/main/packages/components/core/error/error-state-matcher.ts).

Used for checking empty required fields and things that can't be validated client-side.

The submit button is **not disabled**, even if the form is empty or contains invalid fields. When clicked, validation and submission are triggered. The button enters a **Progress** state during submission. You can also display a [Loader Overlay](https://koobiq.io/en/components/loader-overlay.md) over the form during this time.

If validation fails, focus is set to the first field with an error. If the error isn't tied to a specific field, show an alert above the form and focus on it — ensuring visibility even if the form's top section is off-screen.

If the same alert message remains valid on repeated submissions, don't hide and re-show it — instead, fade it out and back in while re-focusing.

[**Example: Validation on submit** (`validation-on-submit`)](https://koobiq.io/examples/validation-on-submit.md)

### Error messages

#### Field-specific message

Field-level error messages are shown below the field, **before** any helper text. If the error message duplicates the helper text, you can replace one with the other.

[**Example: Validation message for specific field** (`validation-message-for-specific-field`)](https://koobiq.io/examples/validation-message-for-specific-field.md)

You don't always need to display an error message just for a required field — marking it as invalid may be enough.

[**Example: Validation no message** (`validation-no-message`)](https://koobiq.io/examples/validation-no-message.md)

#### Global message

General form errors are shown in an alert **above the first field** and focused. The alert appears higher than any informational blocks above the form fields.

In this example, the message appears after clicking the submit button. For mouse users, scrolling to the alert is enough — no need to show a visible focus outline. If the button is activated via keyboard, show a visible focus outline on the alert.

[**Example: Validation message global** (`validation-message-global`)](https://koobiq.io/examples/validation-message-global.md)

#### One required field from several

Some forms require at least **one** of several fields to be filled. In this case, fields aren't marked as invalid after submission. Instead, a general error alert appears above the form. You can list the problematic fields and include pseudo-links to move focus to them.

[**Example: Validation message global with links** (`validation-message-global-with-links`)](https://koobiq.io/examples/validation-message-global-with-links.md)

## Examples

### Validation methods

Angular validators define **what** is invalid — they set error keys on the `FormControl` (`required`, `minlength`, etc.). They do not control **when** those errors are shown to the user. Without any additional mechanism, errors would appear immediately when the page loads, before the user has touched anything.

Koobiq solves this with `ErrorStateMatcher`.

#### ErrorStateMatcher

`ErrorStateMatcher` is a pure display policy. It reads the control's existing errors and the form's submission state, then answers a single question: **should the error be visible right now?**

Validators and the `FormControl` remain unchanged — `ErrorStateMatcher` never adds or removes errors. It only decides when `kbq-form-field` should reveal the `<kbq-error>` children and apply the `kbq-form-field_invalid` CSS class.

In other words, **errors belong to the `FormControl`**. For a required field that starts empty, `control.hasError('required')` returns `true` as soon as the control is created. `ErrorStateMatcher` only decides when to tell the user about it.

**Registration:**

Apply a matcher to all controls inside a component via providers:

```ts
@Component({
    providers: [kbqErrorStateMatcherProvider(ShowOnFormSubmitErrorStateMatcher)]
})
```

Override for a single control using the `[errorStateMatcher]` input (supported by `kbq-tag-list`, `kbq-file-upload`, and similar):

```html
<kbq-file-upload [errorStateMatcher]="myMatcher" ... />
```

### Displaying errors

#### Single validator

[**Example: Validation: single validator** (`validation-basic-single-validator`)](https://koobiq.io/examples/validation-basic-single-validator.md)

#### Multiple validators

[**Example: Validation: multiple validators** (`validation-basic-multiple-validators`)](https://koobiq.io/examples/validation-basic-multiple-validators.md)

### Components

#### Tag list

`kbq-tag-list` supports `ErrorStateMatcher` and integrates with `kbq-form-field` the same way as other controls.

[**Example: Validation tag list** (`validation-tag-list`)](https://koobiq.io/examples/validation-tag-list.md)

#### File upload

File upload components support `ErrorStateMatcher` but have their own layout outside of `kbq-form-field`, so error output is handled differently from input-based controls. See all validation examples on the [File upload](https://koobiq.io/en/components/file-upload.md) page.

### Custom ErrorStateMatcher

Use `ShowRequiredOnSubmitErrorStateMatcher` when you need split behavior:

- If the field is empty, don't show the `required` error until the form is submitted.
- If the field is filled, validate it on blur.

[**Example: Validation on submit with custom matcher** (`validation-on-submit-custom-matcher`)](https://koobiq.io/examples/validation-on-submit-custom-matcher.md)

### Cross-field validation

Some rules compare more than one field: "confirm the password", "the new password must differ from the old
one", "the end date can't precede the start date". A single `FormControl` can't see its sibling's value. So
the natural home for a rule like this is a validator on the `FormGroup`, not on either field.

#### Why a FormGroup error highlights nothing

`<kbq-error>` and the red border come from one thing: the control's `errorState`.

`errorState` is just the return value of `ErrorStateMatcher.isErrorState(control, form)`. The `control` here
is always the field's own `FormControl` — the matcher never sees the group.

So a validator can make the group invalid, and the check still says no. No field turns red. No `<kbq-error>`
appears.

This is not a bug. It's a division of labor: validators decide **what** is invalid, the matcher decides
**when and where** to show it. The fix belongs on the matcher's side.

#### Recommended pattern

Keep the validator on the group — its logic and its error shape stay entirely yours.
`ShowOnCrossFieldErrorStateMatcher` adds the missing half: it shows a group-level error on the controls that
error concerns.

It needs one thing from you: a function that takes each error and returns the names of the controls it's
about, or `null` for an error it doesn't recognize. A name can point into a nested group
(`'passwords.confirm'`) or a `FormArray` row, and the rule itself can live on any ancestor group, not just
the immediate parent.

The error only shows once **every** control it concerns has been touched, or the form is submitted — showing
it earlier would turn a pair red while the user is still typing the second value.

That "any ancestor group" reach has a catch: each control only re-checks its own `errorState` from its own
`ngDoCheck`. If the named controls sit in separate `OnPush` components (each with its own `formGroupName`),
typing in one marks only that component's view dirty — a sibling component showing another named control
won't refresh on its own. Subscribe to the group's `statusChanges` and call `markForCheck()` on the affected
views if your form is split up that way.

[**Example: Validation: cross-field** (`validation-cross-field-password`)](https://koobiq.io/examples/validation-cross-field-password.md)

One matcher instance is enough for any number of rules on a group — the example above puts two rules on one
group, and both are shown by the same matcher.

#### Comparing values that are not primitives

The default `===` comparator silently fails on dates and other object values — use `DateAdapter`'s
`compareDate()` / `compareDateTime()` / `sameDate()`, or your own comparator, instead.

[**Example: Validation: cross-field over dates** (`validation-cross-field-dates`)](https://koobiq.io/examples/validation-cross-field-dates.md)

#### When not to use it

One case doesn't belong in this pattern: "at least one of these fields must be filled". Don't mark any field
invalid for that rule — show a general alert above the form instead. See the
[validation guide](https://koobiq.io/en/other/validation.md) and its "One required field from several" example.

#### Asynchronous rules

A rule only the server can decide goes on the group as an `AsyncValidatorFn`. The answer arrives outside any
event on the field's own view — no click, no keystroke, nothing an `OnPush` view would normally react to — so
it won't re-check itself when the result lands, whether the error ends up on the group or on a child control.
It needs a signal from the group's `statusChanges`.

[**Example: Validation: asynchronous cross-field** (`validation-cross-field-async`)](https://koobiq.io/examples/validation-cross-field-async.md)
