import { StringAsserter } from "https://deno.land/x/typeguardkit@0.33.0/mod.ts";
A StringAsserter
is an Asserter<string>
, with any additional constraints
defined by its StringAsserterOptions
properties.
The minLength
and maxLength
options can be used to set the minimum and
maximum number of characters (as UTF-16 code units) allowed.
The regex
option can be used to specify a regular expression to match
against. regex.pattern
must be a valid HTML <input>
pattern
attribute
value. It is compiled with ^(?:
at the start, )$
at the end, and with the
v
flag. regex.requirements
must not be empty or contain any blank
string
s.
The rules
option can be used to specify validate
functions and their
requirements
. Each validate
function should return true
if value
is
valid according to the rule, and false
otherwise. requirements
must not
be empty or contain any blank string
s.
The provided StringAsserterOptions
are made accessible as properties of the
created StringAsserter
.
A StringAsserter
is also a Validator<string>
with a validate
method,
which checks only that the provided value
meets any constraints defined in
the StringAsserterOptions
, and returns any issues. This can be used to
validate user input client side, where it should already be known that
value
is a string
.
Example:
import { Asserted, StringAsserter } from "typeguardkit";
export const _NonEmptyString = new StringAsserter("NonEmptyString", {
minLength: 1,
});
export type NonEmptyString = Asserted<typeof _NonEmptyString>;
export const _NumericString = new StringAsserter("NumericString", {
regex: { pattern: "\\d+", requirements: ["must be numeric"] },
});
export type NumericString = Asserted<typeof _NumericString>;
export const _Palindrome = new StringAsserter("Palindrome", {
rules: [
{
validate(value) {
if (value.length < 2) {
return true;
}
const forwardValue = value.replace(/[^0-9a-z]/gi, "");
const backwardValue = forwardValue.split("").reverse().join("");
return forwardValue === backwardValue;
},
requirements: ["must be a palindrome"],
},
],
});
export type Palindrome = Asserted<typeof _Palindrome>;