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

Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

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

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay