import { validate } from "https://deno.land/x/abstruct@1.0.0-beta.12/validation.ts";
The validate
executes the Validator and returns a Result type. If validation
succeeds, it returns Ok. If it fails, it returns Err.
If Ok, the value after narrowing of the type is stored.
Examples
Example 1
Example 1
import {
fixedArray,
number,
string,
validate,
type ValidationFailure,
type Validator,
} from "https://deno.land/x/abstruct@$VERSION/mod.ts";
import type {
Assert,
Has,
IsExact,
} from "https://deno.land/std/testing/types.ts";
import { assertEquals } from "https://deno.land/std/testing/asserts.ts";
const Tuple = fixedArray(string, number);
type doTest = Assert<
Has<typeof Tuple, Validator<[unknown, unknown], [string, number]>>,
true
>;
const result = validate(Tuple, [0, ""]);
declare const failure: ValidationFailure;
if (result.isOk()) {
type doTest = Assert<IsExact<typeof result.value, [string, number]>, true>;
} else {
assertEquals(result.value, [failure, failure]);
}
maxFailures
The maximum number of ValidationFailure. It should be positive integer.
The default is Number.MAX_SAFE_INTEGER
.
Example of fail fast:
import {
fixedArray,
number,
string,
validate,
type ValidationFailure,
type Validator,
} from "https://deno.land/x/abstruct@$VERSION/mod.ts";
import type {
Assert,
Has,
IsExact,
} from "https://deno.land/std/testing/types.ts";
import { assertEquals } from "https://deno.land/std/testing/asserts.ts";
const Tuple = fixedArray(string, number);
const result = validate(Tuple, [0, ""], { maxFailures: 1 });
declare const failure: ValidationFailure;
if (result.isErr()) {
assertEquals(result.value, [failure]);
}
Because the validator performs lazy evaluation, limiting the number of errors improves performance.
Parameters
input: In
optional
options: Readonly<ValidateOptions> = [UNSUPPORTED]Returns
Result<RIn, [ValidationFailure, ...ValidationFailure[]]>