import { is, predicates } from "@sealcode/ts-predicates"; import { Context } from "koa"; import { SimpleInput } from "../controls/simple-input.js"; import { FormDataValue } from "../form-types.js"; import { FieldParseResult, FormField } from "./field.js"; import { FormControlContext } from "../controls/form-control.js"; export class RegExpField extends FormField< Required, string, SimpleInput, string > { constructor( required: Required, public regexp: RegExp, public error_message: string, public default_value: string = "" ) { super(required); } predicate = predicates.string; public async isValueValid( _: Context, value: unknown ): Promise<{ valid: boolean; message: string }> { if (!is(value, predicates.string)) { return { valid: false, message: "expected a string" }; } if (this.regexp.exec(value)) { return { valid: true, message: "" }; } return { valid: false, message: this.error_message }; } async parse( _: Context, value: FormDataValue ): Promise> { if (is(value, predicates.string)) { return { parsable: true, parsed_value: value, error: null, }; } else { return { parsable: false, parsed_value: null, error: "Please enter a string", }; } } public getEmptyValue(): string { return this.default_value || ""; } public getControl(): SimpleInput { return new SimpleInput(this, { label: this.label || this.name }); } async getSealiousCreateValue(fctx: FormControlContext): Promise { const { parsed } = await this.getParsedValue( fctx.ctx, fctx.data.raw_values ); return parsed || ""; } async sealiousValueToForm( ctx: Context, sealious_value: string | null ): Promise { return sealious_value || ""; } }