fix: allow comma in amount validation
This commit is contained in:
@@ -1,18 +1,31 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
|
function normalizeAmountInput(rawValue: string): string {
|
||||||
|
const compact = rawValue.trim().replace(/\s+/g, "");
|
||||||
|
|
||||||
|
if (compact.includes(",") && compact.includes(".")) {
|
||||||
|
return compact;
|
||||||
|
}
|
||||||
|
|
||||||
|
return compact.replace(",", ".");
|
||||||
|
}
|
||||||
|
|
||||||
export const amountSchema = z
|
export const amountSchema = z
|
||||||
.string()
|
.string()
|
||||||
.trim()
|
|
||||||
.min(1, "Enter an amount")
|
.min(1, "Enter an amount")
|
||||||
.refine((value) => !Number.isNaN(Number(value)), "Enter a valid number")
|
.transform((value) => normalizeAmountInput(value))
|
||||||
|
.refine(
|
||||||
|
(value) => /^(?:\d+(\.\d+)?|\.\d+)$/.test(value),
|
||||||
|
"Enter a valid number",
|
||||||
|
)
|
||||||
.transform((value) => Number(value))
|
.transform((value) => Number(value))
|
||||||
.refine((value) => Number.isFinite(value), "Enter a valid number")
|
.refine((value) => Number.isFinite(value), "Enter a valid number")
|
||||||
.refine((value) => value > 0, "Amount must be greater than zero")
|
.refine((value) => value > 0, "Amount must be greater than zero")
|
||||||
.refine((value) => value <= 1_000_000_000_000, "Amount is too large");
|
.refine((value) => value <= 1_000_000_000_000, "Amount is too large");
|
||||||
|
|
||||||
export function validateAmount(amount: string):
|
export function validateAmount(
|
||||||
| { ok: true; value: number }
|
amount: string,
|
||||||
| { ok: false; error: string } {
|
): { ok: true; value: number } | { ok: false; error: string } {
|
||||||
const result = amountSchema.safeParse(amount);
|
const result = amountSchema.safeParse(amount);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
@@ -21,6 +34,6 @@ export function validateAmount(amount: string):
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
ok: false,
|
ok: false,
|
||||||
error: result.error.issues[0]?.message ?? "Invalid amount"
|
error: result.error.issues[0]?.message ?? "Invalid amount",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user