PUROGU LADESU

ポエムがメインのブログです。

【ReactNative】TextInputで数字のみに制限する

数値

isNaNで文字の場合は元の値に戻します。

// 変数を文字列で定義した場合
const [amount, setAmount] = React.useState('');

<TextInput
  keyboardType="number-pad"
  placeholder="数字を入力してください"
  onChangeText={(text) => {
    console.log(text);
    setAmount(isNaN(text) ? amount : text);
  }}
  value={amount}
  returnKeyType={'done'}
></TextInput>
// 変数を数値で定義した場合
const [amount, setAmount] = React.useState(0);

<TextInput
  keyboardType="number-pad"
  onChangeText={(text) => {
    console.log(text);
    setAmount(parseInt(isNaN(text) ? amount : text));
  }}
  value={isNaN(amount) ? 0 : amount.toString()}
  returnKeyType={'done'}
></TextInput>

通貨フォーマット

カンマと先頭に円マークを付けます。
フォーカス取得時と喪失時に数値と通貨を変換します。
変数にはフォーマット状態で格納されますので、DBに保存する場合は変換が必要。

const [amount, setAmount] = React.useState('');

// 通貨に戻す
const convertToCurrency = (num) => {
    return '¥' + num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');
};

// 通貨から戻す
const convertFromCurrency = (num) => {
  let temp = num.replace('¥', '');
  temp = temp.replace(',', '');
  temp = temp.replace(' ', '');
  return temp;
};

<TextInput
  keyboardType="number-pad"
  placeholder="¥100 ~ ¥1,000,000"
  onFocus={() => {
    console.log(convertFromCurrency(amount));
    setAmount(convertFromCurrency(amount));
  }}
  onBlur={() => {
    console.log(convertToCurrency(amount));
    if (amount != '') {
      setAmount(convertToCurrency(amount));
    }
  }}
  onChangeText={(text) => {
    setAmount(isNaN(text) ? amount : text);
  }}
  value={amount}
  returnKeyType={'done'}
></TextInput>