Skip to content

Commit

Permalink
refactor: add shouldFormatValue utility function
Browse files Browse the repository at this point in the history
  • Loading branch information
r41ph committed Jan 7, 2025
1 parent 40208bd commit 8cf4080
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -206,3 +206,20 @@ export const formatCurrencyAmount = (

return formattedValue;
};

export const shouldFormatValue = (
decimalPart: string | undefined,
paymentOption: string,
value: string,
): boolean => {
const isDecimalPartValid = decimalPart && decimalPart.length > 2;
const startsWithZero = decimalPart && decimalPart.startsWith('00');
const isCardPayment = paymentOption === PAYMENT_OPTIONS.CARD;

const condition1 = isDecimalPartValid && startsWithZero && isCardPayment;
const condition2 =
(isDecimalPartValid && !startsWithZero && isCardPayment) ||
/^0[0-9]/.test(value);

return condition1 || condition2;
};
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { useMultiStep } from 'components/templates/MultiStepTemplate';
import { findDisplayDenom } from '../DenomLabel/DenomLabel.utils';
import { CURRENCY, CURRENCY_AMOUNT } from './CreditsAmount.constants';
import { CurrencyInputProps } from './CreditsAmount.types';
import { formatCurrencyAmount } from './CreditsAmount.utils';
import { formatCurrencyAmount, shouldFormatValue } from './CreditsAmount.utils';

const CustomSelect = lazy(
() =>
Expand Down Expand Up @@ -56,18 +56,11 @@ export const CurrencyInput = ({

const handleOnChange = useCallback(
(event: ChangeEvent<HTMLInputElement>) => {
// Allow only two decimals when they are all zeros
const value = event.target.value;
const decimalPart = value.split('.')?.[1];
if (
decimalPart &&
decimalPart.length > 2 &&
decimalPart.startsWith('00') &&
paymentOption === PAYMENT_OPTIONS.CARD
) {
if (shouldFormatValue(decimalPart, paymentOption, value)) {
event.target.value = value.slice(0, -1);
}

onChange(event);
handleCurrencyAmountChange(event);
},
Expand All @@ -85,15 +78,8 @@ export const CurrencyInput = ({
shouldValidate: true,
});
}
// Check if the value has a decimal part longer than 2 digits,
// or if the value starts with leading zero/s
if (
(decimalPart &&
decimalPart.length > 2 &&
!decimalPart.startsWith('00') &&
paymentOption === PAYMENT_OPTIONS.CARD) ||
/^0[0-9]/.test(value)
) {

if (shouldFormatValue(decimalPart, paymentOption, value)) {
// remove extra leading zeros
value = value.replace(/^0+/, '');

Expand Down

0 comments on commit 8cf4080

Please sign in to comment.