Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix decimal separator issue in numeric form fields #115

Merged
merged 7 commits into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions src/components/expense-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,17 @@ export type Props = {
runtimeFeatureFlags: RuntimeFeatureFlags
}

const enforceCurrencyPattern = (value: string) =>
value
// replace first comma with #
.replace(/[.,]/, '#')
// remove all other commas
.replace(/[.,]/g, '')
// change back # to dot
.replace(/#/, '.')
// remove all non-numeric and non-dot characters
.replace(/[^\d.]/g, '')

export function ExpenseForm({
group,
expense,
Expand Down Expand Up @@ -210,18 +221,22 @@ export function ExpenseForm({
<FormField
control={form.control}
name="amount"
render={({ field }) => (
render={({ field: { onChange, ...field } }) => (
<FormItem className="sm:order-3">
<FormLabel>Amount</FormLabel>
<div className="flex items-baseline gap-2">
<span>{group.currency}</span>
<FormControl>
<Input
{...field}
className="text-base max-w-[120px]"
type="number"
type="text"
inputMode="decimal"
step={0.01}
placeholder="0.00"
onChange={(event) =>
onChange(enforceCurrencyPattern(event.target.value))
}
onClick={(e) => e.currentTarget.select()}
{...field}
/>
Expand Down Expand Up @@ -428,7 +443,7 @@ export function ExpenseForm({
),
)}
className="text-base w-[80px] -my-2"
type="number"
type="text"
disabled={
!field.value?.some(
({ participant }) =>
Expand All @@ -448,7 +463,9 @@ export function ExpenseForm({
? {
participant: id,
shares:
event.target.value,
enforceCurrencyPattern(
event.target.value,
),
}
: p,
),
Expand Down
3 changes: 1 addition & 2 deletions src/lib/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ export const expenseFormSchema = z
[
z.number(),
z.string().transform((value, ctx) => {
const normalizedValue = value.replace(/,/g, '.')
const valueAsNumber = Number(normalizedValue)
const valueAsNumber = Number(value)
if (Number.isNaN(valueAsNumber))
ctx.addIssue({
code: z.ZodIssueCode.custom,
Expand Down
Loading