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?

【React】郵便番号のフォーム入力中に'-'を自動で追加する

Last updated at Posted at 2024-05-06
sample.html
<div className="postcode">
    郵便番号 <br />
    <input
        value={text}
        onChange={handleChange}
        onKeyUp={handleKeyUp}
        onBlur={handleBlur}
        onCompositionStart={startComposition}
        onCompositionEnd={endComposition}
        type="text"
        placeholder="000-0000"
        maxLength={8}
    />
</div>
sample.tsx
//Enterキー押下時、日本語変換のものかどうか判定する
const [composing, setComposition] = useState(false);
const startComposition = () => setComposition(true);
const endComposition = () => setComposition(false);

const [text, setText] = useState("");
const handleChange = (e: { target: { value: string } }) => {
  setText(() => e.target.value);
};

//郵便番号にハイフンを自動挿入するメソッド
const insertStr = (text: string) => {
  //4桁目が'-(ハイフン)’でない場合で8桁以上入力されている場合は末尾を削除する
  if (text.length >= 8) {
    return text.slice(0, 3) + "-" + text.slice(3, text.length - 1);
  }
  return text.slice(0, 3) + "-" + text.slice(3, text.length);
};

//入力時に郵便番号に自動でハイフンを付けるイベント
const handleKeyUp = (e: React.KeyboardEvent<HTMLInputElement>) => {
  //日本語変換中は処理を行わない
  if (composing) {
    return;
  }
  //削除キーではハイフン追加処理が働かないように制御(8がBackspace、46がDelete)
  const key = e.key;
  if (key == "Backspace" || key == "Delete") {
    return false;
  }

  //3桁目に値が入ったら発動
  if (text.length === 3) {
    setText(insertStr(text));
  }
  //4桁目が'-(ハイフン)’かどうかをチェックし、異なる場合は挿入
  if (text.length >= 3 && text.substring(3, 4) !== "-") {
    setText(insertStr(text));
  }
};

//フォーカスが外れた際に4桁目に'-'がついているかチェック、なければ挿入
const handleBlur = () => {
  //4桁目が'-(ハイフン)’かどうかをチェックし、異なる場合は挿入
  if (text.length >= 3 && text.substring(3, 4) !== "-") {
    setText(insertStr(text));
  }
};
1
0
0

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
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?