1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

<Input type="text" />内に0以上の数値を強制する方法

Last updated at Posted at 2025-04-19

割と時間かかったので載せます。何かの参考になれば幸いです。
少数以外で最初入った"0"も消せます。

コード

以下のメソッドで変換した値を、お好みの方法でinputのvalueにセットしてください。

※コメントでの指摘内容を修正しました 4/20 9:35

const validateInputFloat = (value: string): string => {
    const float = value
      .replace(/^0+(?=\d)/, "")
      .replace(/\.$/, ".0")
      .replace(/^\./, "0.");
    return float.length < 1 || Number.isNaN(+float) ? "0" : float;
  };

挙動

画面収録 2025-04-19 13.44.29.gif

1
1
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?