Skip to content

Commit

Permalink
Input validation (#598)
Browse files Browse the repository at this point in the history
* chore: another one
  • Loading branch information
nick134-bit authored Nov 8, 2024
1 parent 64883fb commit 9090ab7
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 13 deletions.
5 changes: 4 additions & 1 deletion components/AssetInput/WhaleInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,10 @@ ref) => {
onChange={({ target }) => {
onChange({
...token,
amount: amountInputValidation(target.value),
amount: amountInputValidation(
target.value,
tokenInfo?.decimals
),
});
}}
/>
Expand Down
30 changes: 18 additions & 12 deletions util/amountInputValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,26 @@
* General use validation function for when the user supplies a positive decimal value.
* For example it is used with token and slippage amounts.
* @param input The user supplied value
* @param decimals Optional number of decimals to respect
* @returns Validated string that has invalid patterns removed
*/
export const amountInputValidation = (input: string): string => {
const amount = input.
// Limiting the number of characters to be 32
export const amountInputValidation = (input: string, decimals?: number): string => {
let amount = input.
slice(0, 32).
// Disallowing leading decimal place and multiple zeros before decimal place
replace(/^(?:\.|0{2,}\.)/u, '0.').
// Eliminating multiple leading zeros before the numbers between 1-9
replace(/^0+(?=[0-9])/u, '').
// Remove excess zeros after decimal point
replace(/\.(\d+?)0{2,}$/u, '.$10')
// Ensuring multiple decimal points can't be used
return input.indexOf('.') !== amount.lastIndexOf('.') ?
amount.slice(0, amount.indexOf('.') + 1) + amount.slice(amount.indexOf('.')).replaceAll('.', '')
: amount;
replace(/^0+(?=[0-9])/u, '')

// Handle multiple decimal points
if (input.indexOf('.') !== amount.lastIndexOf('.')) {
amount = amount.slice(0, amount.indexOf('.') + 1) +
amount.slice(amount.indexOf('.')).replaceAll('.', '')
}

// If decimals is specified, just limit decimal places without padding
if (decimals !== undefined && amount.includes('.')) {
const [whole, fraction] = amount.split('.')
amount = `${whole}.${fraction.slice(0, decimals)}`
}

return amount
}

0 comments on commit 9090ab7

Please sign in to comment.