refactor: enforce frontend view model boundaries
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { validationMessage } from "@/shared/i18n";
|
||||
|
||||
import { bankToday, moneyCents } from "./form-validation";
|
||||
const ISO_DATE_LENGTH = 10;
|
||||
const MAX_CARD_NAME_LENGTH = 100;
|
||||
const MIN_BALANCE_KOPECKS = -9_223_372_036_854_775_808n;
|
||||
const MAX_BALANCE_KOPECKS = 9_223_372_036_854_775_807n;
|
||||
|
||||
const moneySchema = z.string().refine(
|
||||
(value) => {
|
||||
const cents = moneyCents(value);
|
||||
|
||||
return (
|
||||
cents !== null
|
||||
&& cents >= MIN_BALANCE_KOPECKS
|
||||
&& cents <= MAX_BALANCE_KOPECKS
|
||||
);
|
||||
},
|
||||
{ error: validationMessage("bank.validation.money") },
|
||||
);
|
||||
|
||||
const positiveMoneySchema = moneySchema.refine(
|
||||
(value) => {
|
||||
const cents = moneyCents(value);
|
||||
|
||||
return cents === null || cents > 0n;
|
||||
},
|
||||
{ error: validationMessage("bank.validation.positive") },
|
||||
);
|
||||
|
||||
const bankDateSchema = z
|
||||
.string()
|
||||
.refine(
|
||||
value =>
|
||||
/^\d{4}-\d{2}-\d{2}$/.test(value)
|
||||
&& value >= "0001-01-01"
|
||||
&& !Number.isNaN(Date.parse(`${value}T00:00:00Z`))
|
||||
&& new Date(`${value}T00:00:00Z`).toISOString().slice(0, ISO_DATE_LENGTH)
|
||||
=== value
|
||||
&& value <= bankToday(),
|
||||
{ error: validationMessage("bank.validation.date") },
|
||||
);
|
||||
|
||||
const bankCardSchema = z.object({
|
||||
bankName: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(
|
||||
MAX_CARD_NAME_LENGTH,
|
||||
validationMessage("bank.validation.bankName")(undefined),
|
||||
),
|
||||
lastFour: z.string().refine(value => !value || /^\d{4}$/.test(value), {
|
||||
error: validationMessage("bank.validation.lastFour"),
|
||||
}),
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, validationMessage("bank.validation.name")(undefined))
|
||||
.max(
|
||||
MAX_CARD_NAME_LENGTH,
|
||||
validationMessage("bank.validation.name")(undefined),
|
||||
),
|
||||
openingBalance: moneySchema,
|
||||
openingDate: bankDateSchema,
|
||||
paymentSystem: z
|
||||
.enum(["", "mir", "visa", "mastercard"], {
|
||||
error: validationMessage("bank.validation.paymentSystem"),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
|
||||
type BankCardValues = z.infer<typeof bankCardSchema>;
|
||||
|
||||
export {
|
||||
bankCardSchema,
|
||||
type BankCardValues,
|
||||
bankDateSchema,
|
||||
positiveMoneySchema,
|
||||
};
|
||||
Reference in New Issue
Block a user