diff --git a/.changeset/thin-chairs-stare.md b/.changeset/thin-chairs-stare.md new file mode 100644 index 0000000..be4ce1c --- /dev/null +++ b/.changeset/thin-chairs-stare.md @@ -0,0 +1,5 @@ +--- +"formgator": patch +--- + +Empty `textarea()` properly returns `null` diff --git a/src/validators/textarea.ts b/src/validators/textarea.ts index 9ae6199..d48cbe3 100644 --- a/src/validators/textarea.ts +++ b/src/validators/textarea.ts @@ -9,20 +9,31 @@ import { type FormInput, failures, methods, succeed } from "../definitions.js"; * - `maxlength` - Maximum length of the input. * - `minlength` - Minimum length of the input. */ +export function textarea(attributes?: { + required?: false; + maxlength?: number; + minlength?: number; +}): FormInput & { trim: () => FormInput }; +export function textarea(attributes: { + required: true; + maxlength?: number; + minlength?: number; +}): FormInput & { trim: () => FormInput }; export function textarea( attributes: { required?: boolean; maxlength?: number; minlength?: number; } = {}, -): FormInput & { trim: () => FormInput } { +): FormInput & { trim: () => FormInput } { return { ...methods, attributes, safeParse: (data, name) => { const value = data.get(name); if (typeof value !== "string") return failures.type(); - if (attributes.required && value === "") return failures.required(); + if (value === "") + return attributes.required ? failures.required() : succeed(null); if (attributes.maxlength && value.length > attributes.maxlength) return failures.maxlength(attributes.maxlength); if (attributes.minlength && value.length < attributes.minlength) @@ -31,7 +42,7 @@ export function textarea( }, /** Removes the leading and trailing white space from the value. */ trim() { - return this.transform((value) => value.trim()); + return this.transform((value) => (value ?? "").trim()); }, }; }