Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

1
0

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にセットしてください。

※最初の"."が放置されていたので修正しました

  const validateInputFloat = (value: string): string =>
    value.split(".").length < 3 && /^(\d+\.?\d*|\.\d+)$/.test(value)
      ? value
          .replace(/^0+(?=\d)/, "")
          .replace(/^\./, "0.")
          .replace(/\.$/, ".0")
      : "0";

挙動

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

1
0
3

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
q-1-p

@q-1-p

新しい技術やサービスが好きな若者です
jisou
「科学的根拠を基にしたアウトプットカリキュラム」 現役専門プログラミングコーチングJISOUのメンバーによる記事投稿をしています。 コミュニティの詳細はホームページをご覧ください。

Comments

nmcr5575
@nmcr5575

.1 → 0.1 にならない
0.0000 → 0 にならない
8.90 → 8.9 にならない
12.34.56 → 0 にならない
.... → ....0 になる

この辺は仕様でしょうか?

3
q-1-p
@q-1-p

最後に0が残っていても数値として計算できるので、後ろの0は残しておいています。
"."が複数あったり、最初にあったりしても検出していないのは、考慮漏れだったのでコード修正しました。
コメントありがとうございます。

0
ibyrjbf
@ibyrjbf

value.split(".").length < 3 && /^(\d+\.?\d*|\.\d+)$/.test(value)

この条件式は !isNaN(value) でいいのでは?

0

Let's comment your feelings that are more than good

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details

Being held Article posting campaign

1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address