Documentation navigation

Published API · 0.1.0-rc.1

foldkit · fieldValidation

Published foldkit API declarations for fieldValidation.

./fieldValidation

@wsagency/wseffect-foldkit · MIT · source · MIT license · WS-AGENCY-NOTICE · THIRD-PARTY-NOTICES

This entry point is published in @wsagency/wseffect-foldkit@0.1.0-rc.1. Import it from the package subpath shown below; the signatures and documentation are read from the installed package declarations.

import * as Wseffect from '@wsagency/wseffect-foldkit/fieldValidation'

Exported declarations

allValid

Returns true when every field is acceptable per its rules, by `isValid`. Each pair is a field's `[state, rules]`. The pairs in one call share a value type, so a call gates fields of a single type; for a form that mixes types, call `allValid` once per type and combine the results with `&&`. Use for form-level submit gates.

allValid: <A>(pairs: ReadonlyArray<readonly [Field<A>, Rules<A>]>) => boolean

anyInvalid

Returns true when any state in the input has tag `Invalid`. Use for "this step/section has errors" affordances, independent of rules.

anyInvalid: (states: ReadonlyArray<Field<unknown>>) => boolean

Field

The four-state union that represents a field's value in the Model.

export type Field<A> = NotValidated<A> | Validating<A> | Valid<A> | Invalid<A>;

Field

Builds the four-state `Field` Schema for a value of the given Schema. Put the result in your Model. The value Schema should match what the control actually holds as the user edits, not the type you parse it into: `Field(Schema.String)` for text inputs, `Field(Schema.Array(Schema.String))` for a multi-select. A scalar like a checkbox's boolean usually stays plain `Schema.Boolean` in the Model; wrap it in `Field` only when it needs the validation lifecycle. Validation rules stay separate, in a `makeRules` bundle.

Field: <A, I>(valueSchema: Schema.Codec<A, I>) => Schema.Union<readonly [Schema.TaggedStruct<"NotValidated", {
    readonly value: Schema.Codec<A, I, never, never>;
}>, Schema.TaggedStruct<"Validating", {
    readonly value: Schema.Codec<A, I, never, never>;
}>, Schema.TaggedStruct<"Valid", {
    readonly value: Schema.Codec<A, I, never, never>;
}>, Schema.TaggedStruct<"Invalid", {
    readonly value: Schema.Codec<A, I, never, never>;
    readonly errors: Schema.NonEmptyArray<Schema.String>;
}>]>

Invalid

The `Invalid` state: one or more rules failed. Carries a non-empty `errors` array.

export type Invalid<A> = Readonly<{
    _tag: 'Invalid';
    value: A;
    errors: Array.NonEmptyReadonlyArray<string>;
}>;

Invalid

Constructs an `Invalid` state.

Invalid: <A>(field: Readonly<{
    value: A;
    errors: Array.NonEmptyReadonlyArray<string>;
}>) => Invalid<A>

isInvalid

Returns true when the state's tag is `Invalid`. Tag-only predicate; unlike `!isValid(rules)(state)`, this does not treat `NotValidated` or `Validating` as errors. Use for "has the user seen a rule failure on this field?" affordances like red borders or per-step error indicators.

isInvalid: (state: Field<unknown>) => boolean

isRequired

Returns true when the rules mark the field as required. Useful for rendering affordances like a `*` next to required field labels.

isRequired: <A>(rules: Rules<A>) => boolean

isValid

Returns true when the field's current state is acceptable given its rules. For required fields, only `Valid` returns `true`. For optional fields, `Valid` or `NotValidated` both return `true`. `Invalid` and `Validating` always return `false`. The name is distinct from the `Valid` tag on purpose: `isValid` answers "is this state an acceptable result?", which for an optional field is broader than `_tag === 'Valid'`. For pattern-matching on the state itself, check the `_tag` directly.

isValid: <A>(rules: Rules<A>) => (state: Field<A>) => boolean

makeRules

Creates a `Rules` bundle from options. The value type defaults to `string`; for other field values, annotate it: `makeRules<ReadonlyArray<Tag>>({ ... })`.

makeRules: <A = string>(options?: MakeRulesOptions<A>) => Rules<A>

MakeRulesOptions

Options accepted by `makeRules`.

export type MakeRulesOptions<A> = Readonly<{
    /** When present, the field is required: empty values become `Invalid`
     *  with the given message, and `isValid` requires `Valid`. Absent
     *  means the field is optional: empty values stay `NotValidated`, and
     *  `isValid` accepts `Valid` or `NotValidated`. */
    required?: RuleMessage<A>;
    rules?: ReadonlyArray<Rule<A>>;
    /** Predicate for what counts as "empty" for this field. Defaults to empty
     *  string and empty array; every other value is treated as present. Pass
     *  `(value) => value.trim() === ''` to treat whitespace-only input as empty. */
    isEmpty?: (value: A) => boolean;
}>;

match

Handles every field state. `onNotValidated`, `onValidating`, and `onValid` each receive the state's `value`; `onInvalid` alone receives the whole `{ value, errors }` payload object because `Invalid` carries two fields. Data-first with the field, or data-last for pipelines.

match: {
    <A, B, C = B, D = B, F = B>(handlers: Readonly<{
        onNotValidated: (value: A) => B;
        onValidating: (value: A) => C;
        onValid: (value: A) => D;
        onInvalid: (payload: Readonly<{
            value: A;
            errors: Array.NonEmptyReadonlyArray<string>;
        }>) => F;
    }>): (self: Field<A>) => B | C | D | F;
    <A, B, C = B, D = B, F = B>(self: Field<A>, handlers: Readonly<{
        onNotValidated: (value: A) => B;
        onValidating: (value: A) => C;
        onValid: (value: A) => D;
        onInvalid: (payload: Readonly<{
            value: A;
            errors: Array.NonEmptyReadonlyArray<string>;
        }>) => F;
    }>): B | C | D | F;
}

NotValidated

The `NotValidated` state: user hasn't interacted yet.

export type NotValidated<A> = Readonly<{
    _tag: 'NotValidated';
    value: A;
}>;

NotValidated

Constructs a `NotValidated` state.

NotValidated: <A>(field: Readonly<{
    value: A;
}>) => NotValidated<A>

Rule

import { Predicate, Schema } from 'effect';
/** An error message for a rule: either a static string, or a function that receives the invalid value. */
export type RuleMessage<A> = string | ((value: A) => string);
/** A tuple of a predicate and error message used for field validation. */
export type Rule<A> = readonly [Predicate.Predicate<A>, RuleMessage<A>];
/** Resolves a `RuleMessage` to a concrete string, applying it to the value when the message is a function. */
export declare const resolveMessage: <A>(message: RuleMessage<A>, value: A) => string;
/** Creates a `Rule` that checks if a string meets a minimum length. */
export declare const minLength: (min: number, message?: RuleMessage<string>) => Rule<string>;
/** Creates a `Rule` that checks if a string does not exceed a maximum length. */
export declare const maxLength: (max: number, message?: RuleMessage<string>) => Rule<string>;
/** Creates a `Rule` that checks if a string matches a regular expression. */
export declare const pattern: (regex: RegExp, message?: RuleMessage<string>) => Rule<string>;
/** Creates a `Rule` that checks if a string is a valid email format. */
export declare const email: (message?: RuleMessage<string>) => Rule<string>;
/** Creates a `Rule` that checks if a string is a valid URL format.
 *
 *  By default the URL must include an `http://` or `https://` protocol.
 *  Pass `{ requireProtocol: false }` to accept bare domains. */
export declare const url: (options?: Readonly<{
    message?: RuleMessage<string>;
    requireProtocol?: boolean;
}>) => Rule<string>;
/** Creates a `Rule` that checks if a string begins with a specified prefix. */
export declare const startsWith: (prefix: string, message?: RuleMessage<string>) => Rule<string>;
/** Creates a `Rule` that checks if a string ends with a specified suffix. */
export declare const endsWith: (suffix: string, message?: RuleMessage<string>) => Rule<string>;
/** Creates a `Rule` that checks if a string contains a specified substring. */
export declare const includes: (substring: string, message?: RuleMessage<string>) => Rule<string>;
/** Creates a `Rule` that checks if a string exactly matches an expected value. */
export declare const equals: (expected: string, message?: RuleMessage<string>) => Rule<string>;
/** Creates a `Rule` that checks if a string is one of a specified set of allowed values. */
export declare const oneOf: (values: ReadonlyArray<string>, message?: RuleMessage<string>) => Rule<string>;
/** Creates a `Rule` that checks an array holds at least `min` items. */
export declare const minItems: (min: number, message?: RuleMessage<ReadonlyArray<unknown>>) => Rule<ReadonlyArray<unknown>>;
/** Creates a `Rule` that checks an array holds at most `max` items. */
export declare const maxItems: (max: number, message?: RuleMessage<ReadonlyArray<unknown>>) => Rule<ReadonlyArray<unknown>>;
/** Creates a `Rule` that passes when the value decodes through `schema`.
 *
 *  Use it to reuse a Schema you already maintain (a domain codec, a refined or
 *  branded type you decode to on submit) as a field rule, so the rule stays in
 *  sync with the schema instead of duplicating its logic. It does nothing a
 *  custom rule can't, so prefer the dedicated rules for plain checks. Decoding
 *  is synchronous: the schema must decode without running an effect. */
export declare const fromSchema: <A, I>(schema: Schema.Codec<A, I>, message: RuleMessage<I>) => Rule<I>;

Rules

A field's validation rules: the required message (if any), the list of rules, and an empty predicate. Produced by `makeRules`; consumed by the module's operations (`validate`, `validateAll`, `isValid`, `isRequired`). The fields are accessible but treating them as stable is discouraged. Prefer the operations so internal shape changes don't break callers.

export type Rules<A> = Readonly<{
    requiredMessage: Option.Option<RuleMessage<A>>;
    rules: ReadonlyArray<Rule<A>>;
    isEmpty: (value: A) => boolean;
}>;

Valid

The `Valid` state: every rule passed.

export type Valid<A> = Readonly<{
    _tag: 'Valid';
    value: A;
}>;

Valid

Constructs a `Valid` state.

Valid: <A>(field: Readonly<{
    value: A;
}>) => Valid<A>

validate

Validates a new value and returns the next field state. For required fields, an empty value produces `Invalid` with the required message. For optional fields, an empty value produces `NotValidated`. Non-empty values run through the field's rules; the first failure becomes `Invalid`, otherwise the result is `Valid`.

validate: <A>(rules: Rules<A>) => (value: A) => Field<A>

validateAll

Like `validate` but collects every failing rule into the `Invalid` state's errors array instead of stopping at the first.

validateAll: <A>(rules: Rules<A>) => (value: A) => Field<A>

Validating

The `Validating` state: async validation is in flight.

export type Validating<A> = Readonly<{
    _tag: 'Validating';
    value: A;
}>;

Validating

Constructs a `Validating` state.

Validating: <A>(field: Readonly<{
    value: A;
}>) => Validating<A>