Skip to content

Overview

The DateInput component utilizes the svelte-flatpickr library to create a flexible and user-friendly date and time picker input. It provides a range of configuration options, allowing easy customization of the date picker's behavior to suit various needs.

Additionally, the component seamlessly handles form validation and error handling. It communicates with the parent Form component to manage the validation process and display any relevant errors associated with the date input.

Overall, the DateInput component enhances the user experience by offering a powerful and customizable date and time picker while seamlessly integrating with the parent Form component for validation and error management.

Implementation

Below is how the DateInput component is implemented.

svelte
<script>
  import { getContext, createEventDispatcher } from "svelte"
  import { fade } from "svelte/transition"
  import { key } from "./form"
  import { uniqueId } from "lodash"
  import Flatpickr from 'svelte-flatpickr'

  export let name
  export let label = name
  export let required = false
  export let showRequiredIndicator = true
  export let enableTime = false
  export let noCalendar = false
  export let dateFormat =  enableTime ? "Y-m-d H:i" : "Y-m-d"
  export let altFormat = enableTime ? "Y-m-d H:i" : "Y-m-d" // enableTime ? "F j, Y" : "F j, Y H:i" // "Y-m-d H:i" //
  export let altInput = true
  export let weekNumbers = false

  let id = uniqueId(name)
  let pickerId = uniqueId(name)
  let fullPickerId = `#${pickerId}`
  let dispatch = createEventDispatcher()

  const { touched, errors, data } = getContext(key)
    let formattedValue;

    const options = {
      enableTime, noCalendar, dateFormat, altFormat, altInput,
      weekNumbers,
      element: fullPickerId,
      onChange(selectedDates, dateStr) {
        console.log("changed", {name, selectedDates, dateStr})
      }
    };

    function handleChange(event) {
        const [ selectedDates, dateStr ] = event.detail;
        console.log({ selectedDates, dateStr });
    }


  $: hasError = $touched[name] && $errors[name]?.length
  $: error = $errors[name]?.join(", ")

</script>

<div class="form-control">
  <label class="label flex" for={id}>
    <span class="label-text">
      {label}
      {#if required && showRequiredIndicator}
        <span class="text-red-600" in:fade out:fade>*</span>
      {/if}
    </span>
  </label>

  <Flatpickr {options} bind:value={$data[name]} bind:formattedValue on:change={handleChange} {name} class="border border-gray-300 border-solid h-10 rounded-sm" />

  {#if hasError}
    <label class="label" for={id} in:fade out:fade>
      <span class="label-text-alt text-red-900">{error}</span>
    </label>
  {/if}
</div>

Released under the MIT License.