diff --git a/packages/checkout/widgets-lib/src/widgets/add-tokens/functions/amountValidation.ts b/packages/checkout/widgets-lib/src/widgets/add-tokens/functions/amountValidation.ts index 0ff5232946..d87d2f2880 100644 --- a/packages/checkout/widgets-lib/src/widgets/add-tokens/functions/amountValidation.ts +++ b/packages/checkout/widgets-lib/src/widgets/add-tokens/functions/amountValidation.ts @@ -1,4 +1,4 @@ -const VALID_NUMBER_REGEX = /^[0-9]+(\.[0-9]+)?$/; +const VALID_NUMBER_REGEX = /^(0|[1-9]\d*)(\.\d*)?$/; /** * Validate the amount input @@ -6,11 +6,10 @@ const VALID_NUMBER_REGEX = /^[0-9]+(\.[0-9]+)?$/; * @returns An object containing the sanitized value, the float amount, and a boolean indicating if the amount is valid */ export const validateToAmount = (amount: string) => { - const value = amount || '0'; + const value = amount || ''; const sanitizedValue = value.replace(/^0+(?=\d)/, ''); - const floatAmount = parseFloat(sanitizedValue); + const isValid = VALID_NUMBER_REGEX.test(sanitizedValue); + const floatAmount = isValid ? parseFloat(sanitizedValue) : NaN; - const isValid = VALID_NUMBER_REGEX.test(sanitizedValue) && floatAmount > 0; - - return { value: sanitizedValue, amount: floatAmount, isValid }; + return { value: sanitizedValue, amount: floatAmount, isValid: isValid && floatAmount > 0 }; }; diff --git a/packages/checkout/widgets-lib/src/widgets/add-tokens/views/AddTokens.tsx b/packages/checkout/widgets-lib/src/widgets/add-tokens/views/AddTokens.tsx index 4b234cb375..7af5df8f8e 100644 --- a/packages/checkout/widgets-lib/src/widgets/add-tokens/views/AddTokens.tsx +++ b/packages/checkout/widgets-lib/src/widgets/add-tokens/views/AddTokens.tsx @@ -188,22 +188,25 @@ export function AddTokens({ const handleOnAmountInputChange = (event: ChangeEvent) => { const { value, amount, isValid } = validateToAmount(event.target.value); - if (!isValid && amount < 0) { - return; + if (isValid || amount === 0 || value === '') { + setInputValue(value); + + if (amount > 0) { + setSelectedAmount(value); + + track({ + userJourney: UserJourney.ADD_TOKENS, + screen: 'InputScreen', + control: 'AmountInput', + controlType: 'TextInput', + extras: { + toAmount: value, + }, + }); + } else { + setSelectedAmount(''); + } } - - setInputValue(value); - setSelectedAmount(value); - - track({ - userJourney: UserJourney.ADD_TOKENS, - screen: 'InputScreen', - control: 'AmountInput', - controlType: 'TextInput', - extras: { - toAmount: value, - }, - }); }; const { @@ -550,7 +553,7 @@ export function AddTokens({ {t('views.ADD_TOKENS.tokenSelection.buttonText')} ) : ( {t('views.ADD_TOKENS.tokenSelection.tokenLabel')} @@ -560,9 +563,9 @@ export function AddTokens({ handleOnAmountInputChange(value)} + onChange={(event) => handleOnAmountInputChange(event)} placeholder="0" maxTextSize="xLarge" /> @@ -590,7 +593,7 @@ export function AddTokens({ - {selectedToken && fromAddress && inputValue && ( + {selectedToken && fromAddress && selectedAmount && ( <>