DEV Community

Beaver Bridge
Beaver Bridge

Posted on

Svelte에서 input type이 date 일 때, 월/일에 0으로 시작하는 날짜를 넣으면 기존 입력 사라지는 문제

<script>
  let date1 = "2024-01-01";
  let date2 = "2024-01-02";
</script>

<p>date1: <input type="date" bind:value={date1} max="9999-12-31" /></p>
<p>date2: <input type="date" value={date2} max="9999-12-31" /></p>
Enter fullscreen mode Exit fullscreen mode

이렇게 만들면 bind:value가 걸린 필드에 2023.01.01 을 입력하려할 때 월/일 에 0을 입력하면 기존에 입력된 내용이 사라진다.
github에 물어봐도, 이미 2022년에 누가 고쳐달라고 올린 이슈가 있던데 아직도 안 고쳐진걸로 봐선 시간이 걸릴 것 같아서 컴포넌트로 만들었다.

<script>
  import { createEventDispatcher } from "svelte";

  export let value;
  export let type = "date";
  export let max = "9999-12-31";
  export { _class as class };
  let _class = "";

  let downedKey;

  const handleKeyDown = (event) => {
    downedKey = event.key;
    dispatch("keydown", event);
  };

  const handleChanged = (event) => {
    const newValue = event.target.value;
    if (downedKey === "Backspace" || downedKey === "Delete" || newValue) {
      value = newValue;
      dispatch("change", event);
    }
  };
</script>

<input
  {type}
  {value}
  {max}
  on:keydown={handleKeyDown}
  on:change={handleChanged}
  class=" {_class}"
/>
Enter fullscreen mode Exit fullscreen mode

이렇게 하면 백스페이스나 삭제버튼을 눌러서 지운게 아니면 데이터가 날아가지 않게 된다.

테스트는 여기서 해볼 수 있다.

https://svelte.dev/repl/301e4f0596534cfe90b5f72eb22d09ae?version=4.2.8

Retry later

Top comments (0)

Retry later
👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay