shelving
Version:
Toolkit for using data in JavaScript.
39 lines (38 loc) • 1.69 kB
TypeScript
import type { SchemaOptions } from "./Schema.js";
import { Schema } from "./Schema.js";
/** Function that sanitizes a string. */
export type Sanitizer = (str: string) => string;
/** Options for `StringSchema` */
export interface StringSchemaOptions extends SchemaOptions {
readonly value?: string | undefined;
readonly min?: number | undefined;
readonly max?: number | undefined;
}
/**
* Schema that defines a valid string.
*
* @example
* const schema = new StringSchema({ default: 'abc', required: true, min: 2, max: 6, match: /^[a-z0-9]+$/, trim: true });
* schema.validate('def'); // Returns 'def'
* schema.validate('abcdefghijk'); // Returns 'abcdef' (due to max)
* schema.validate(undefined); // Returns 'abc' (due to value)
* schema.validate(' ghi '); // Returns 'ghi' (due to schema.trim, defaults to true)
* schema.validate(1234); // Returns '1234' (numbers are converted to strings)
* schema.validate('---'); // Throws 'Incorrect)
* schema.validate(true); // Throws 'Must be)
* schema.validate(''); // Throws Required
* schema.validate('j'); // Throws 'Minimum 3 chaacters'
*/
export declare class StringSchema extends Schema<string> {
readonly value: string;
readonly min: number;
readonly max: number;
constructor({ min, max, value, ...options }: StringSchemaOptions);
validate(unsafeValue?: unknown): string;
/** Sanitize the string by removing unwanted characters. */
sanitize(str: string): string;
}
/** Valid string, e.g. `Hello there!` */
export declare const STRING: StringSchema;
/** Valid string, `Hello there!`, with more than one character. */
export declare const REQUIRED_STRING: StringSchema;