Changeset View
Changeset View
Standalone View
Standalone View
web/cashtab/src/utils/validation.js
import BigNumber from 'bignumber.js'; | |||||
import { currency } from '@components/Common/Ticker.js'; | import { currency } from '@components/Common/Ticker.js'; | ||||
// Validate cash amount | // Validate cash amount | ||||
export const shouldRejectAmountInput = ( | export const shouldRejectAmountInput = ( | ||||
cashAmount, | cashAmount, | ||||
selectedCurrency, | selectedCurrency, | ||||
fiatPrice, | fiatPrice, | ||||
totalCashBalance, | totalCashBalance, | ||||
) => { | ) => { | ||||
// Take cashAmount as input, a string from form input | // Take cashAmount as input, a string from form input | ||||
let error = false; | let error = false; | ||||
let testedAmount = cashAmount; | let testedAmount = new BigNumber(cashAmount); | ||||
if (selectedCurrency === 'USD') { | if (selectedCurrency === 'USD') { | ||||
testedAmount = (cashAmount / fiatPrice).toFixed(8); | // Ensure no more than 8 decimal places | ||||
testedAmount = new BigNumber(fiatToCrypto(cashAmount, fiatPrice)); | |||||
} | } | ||||
// Validate value for > 0 | // Validate value for > 0 | ||||
if (isNaN(testedAmount)) { | if (isNaN(testedAmount)) { | ||||
error = 'Amount must be a number'; | error = 'Amount must be a number'; | ||||
} else if (testedAmount <= 0) { | } else if (testedAmount.lte(0)) { | ||||
error = 'Amount must be greater than 0'; | error = 'Amount must be greater than 0'; | ||||
} else if (testedAmount < currency.dust) { | } else if (testedAmount.lt(currency.dust)) { | ||||
error = `Send amount must be at least ${currency.dust} ${currency.ticker}`; | error = `Send amount must be at least ${currency.dust} ${currency.ticker}`; | ||||
} else if (testedAmount > totalCashBalance) { | } else if (testedAmount.gt(totalCashBalance)) { | ||||
error = `Amount cannot exceed your ${currency.ticker} balance`; | error = `Amount cannot exceed your ${currency.ticker} balance`; | ||||
} else if (!isNaN(testedAmount) && testedAmount.toString().includes('.')) { | } else if (!isNaN(testedAmount) && testedAmount.toString().includes('.')) { | ||||
if (testedAmount.toString().split('.')[1].length > 8) { | if (testedAmount.toString().split('.')[1].length > 8) { | ||||
error = `${currency.ticker} transactions do not support more than 8 decimal places`; | error = `${currency.ticker} transactions do not support more than 8 decimal places`; | ||||
} | } | ||||
} | } | ||||
// return false if no error, or string error msg if error | // return false if no error, or string error msg if error | ||||
return error; | return error; | ||||
}; | }; | ||||
export const fiatToCrypto = (fiatAmount, fiatPrice) => { | |||||
// Return a string with no more than 8 decimal places | |||||
let cryptoAmount = new BigNumber(fiatAmount) | |||||
.div(new BigNumber(fiatPrice)) | |||||
.toFixed(8); | |||||
return cryptoAmount; | |||||
}; |