Skip to content

Commit

Permalink
fix: textarea() returns null when empty
Browse files Browse the repository at this point in the history
  • Loading branch information
GauBen committed Oct 11, 2024
1 parent a0da4cb commit a2d9658
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/thin-chairs-stare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"formgator": patch
---

Empty `textarea()` properly returns `null`
17 changes: 14 additions & 3 deletions src/validators/textarea.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | null> & { trim: () => FormInput<string> };
export function textarea(attributes: {
required: true;
maxlength?: number;
minlength?: number;
}): FormInput<string> & { trim: () => FormInput<string> };
export function textarea(
attributes: {
required?: boolean;
maxlength?: number;
minlength?: number;
} = {},
): FormInput<string> & { trim: () => FormInput<string> } {
): FormInput<string | null> & { trim: () => FormInput<string> } {
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)
Expand All @@ -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());
},
};
}

0 comments on commit a2d9658

Please sign in to comment.