Skip to content

Commit

Permalink
Fix Error Handling in amount field of Expense Form
Browse files Browse the repository at this point in the history
When Invalid expression in amount field was submitted, it would throw an
error. It has been wrapped in try block.
  • Loading branch information
parthokunda committed Jul 27, 2024
1 parent 2531142 commit 0b851ad
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 15 deletions.
22 changes: 14 additions & 8 deletions src/components/expense-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -332,23 +332,29 @@ export function ExpenseForm({
placeholder="0.00"
onChange={(event) => {
let v = (event.target.value)
if (v === ''){
if (v === '') {
setEvaluatedAmount('0')
}
else{
try{
const evaluatedValue = Number(mexp.eval(v)).toFixed(2).replace(/\.?0+$/, '') // replace trailing zeros
} else {
try {
const evaluatedValue = Number(mexp.eval(v))
.toFixed(2)
.replace(/\.?0+$/, '') // replace trailing zeros
setEvaluatedAmount(evaluatedValue)
const income = Number(evaluatedValue) < 0
setIsIncome(income)
if (income) form.setValue('isReimbursement', false)
}
catch{
if (income)
form.setValue('isReimbursement', false)
} catch {
setEvaluatedAmount('Invalid Expression')
}
}
onChange(v)
}}
onFocus={(e) => {
// we're adding a small delay to get around safaris issue with onMouseUp deselecting things again
const target = e.currentTarget
setTimeout(() => target.select(), 1)
}}
{...field}
/>
</FormControl>
Expand Down
24 changes: 17 additions & 7 deletions src/lib/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,23 @@ export const expenseFormSchema = z
[
z.number(),
z.string().transform((value, ctx) => {
const valueAsNumber = Number(mexp.eval(value).toFixed(2).replace(/\.?0+$/, ''))
if (Number.isNaN(valueAsNumber))
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Invalid number.',
})
return Math.round(valueAsNumber * 100)
let valueAsNumber = NaN;
try {
valueAsNumber =
Number(
mexp
.eval(value)
.toFixed(2)
.replace(/\.?0+$/, '') // replace trailing zeros
)
} finally {
if (Number.isNaN(valueAsNumber))
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Invalid number.',
})
return Math.round(valueAsNumber * 100)
}
}),
],
{ required_error: 'You must enter an amount.' },
Expand Down

0 comments on commit 0b851ad

Please sign in to comment.