8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

えるしってるか。口座番号は数字じゃない

Last updated at Posted at 2017-01-22

入力項目で、数字のみを入れて欲しい場合、どうすればいいだろう。
例えば、金額欄にhogehogeとか入れられても困るのである。
そいつをvalidationで弾きたい。
postされたあとにサーバサイドで弾いてもよいが、どちらかというと入力時にブラウザのjsチェックで弾き、入力そのものをなかったことにしたい。
金額欄に 123456 と入れようとしてうっかりtypo、 12345t6 と入れてもjsでこの t を取り除き、 123456 という形に整形したい

そういうときどうするか?

jsだとみんな大好きparseInt先生を使う。
一例: parseInt(value, 10)

ところが問題がある。
一見数字に見えるが、実は口座番号は数字ではない。
どのあたりが数字でないかというと先頭に 0 が許容されている。
そのため

const value = '00123456';
const output = parseInt(value, 10); // 123456

入力者的には何回ゼロを入力欄に入れてもゼロが無視される結果が返る。
ユーザーはどうするかっていうとキレる。あるいはサポートに鬼電話。
口座番号が絡んでいる時点でこれはお金の問題である。つまり割とセンシティブな話になる。

そこで発想を変える。
ジョジョ逆に考えるんだ。口座番号は0-9までだけが許容された文字列だと。
ということでこうやって数字以外を置き換える。
ありがたいアドバイス に基づき改定しました

const value = '00123456';
const output = value.replace(/\D/g, ''); // 00123456

補足:
\D : 半角数字以外
\d : 半角数字
意味的には以下に同じ
const output = value.replace(/[^0-9^\.]/g, ''); // 00123456

これで事態は解決する

8
4
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
8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?