diff --git a/src/lib/components/FormFlow/Counter.svelte b/src/lib/components/FormFlow/Counter.svelte index 2f051bc..70a1f2d 100644 --- a/src/lib/components/FormFlow/Counter.svelte +++ b/src/lib/components/FormFlow/Counter.svelte @@ -3,6 +3,13 @@ import { activeResponses } from "$lib/store"; import { getContext, onMount } from "svelte"; + onMount( () => { + if ($activeResponses[id].data[component.id] === undefined) { + $activeResponses[id].data[component.id] = + component.initialValue ?? 0; + } + }); + // Set default values if fields are left as undefined export let component: Counter; const min = component.min ?? 0; @@ -15,35 +22,19 @@ export const id: number = getContext("id") $: count = Number($activeResponses[id].data[component.id]) - - onMount( () => { - if (Number($activeResponses[id].data[component.id]) === undefined) { - $activeResponses[id].data[component.id] = 0; - }} - ) // Count is considered to be valid if error // is undefined! export let error: string | undefined = undefined; - /** - * Ensure that the input is an actual number, - * not less than min, and not greater than max. - */ - const validateInput = () => { - if (!Number.isInteger(count)) { - // If the inputted value is NOT a number, this will set the counter - // to its initial value - if (count == undefined || count == null || count.toString().trim().length == 0) { - error = undefined; - count = initialValue; - } else { - error = "Number must be an integer!"; - } - } else if (parseInt(count.toString()) < min) { - error = `Number must be greater than ${min}!`; - } else if (parseInt(count.toString()) > max) { - error = `Number must be less than ${max}!`; + $: { + const num = $activeResponses[id].data[component.id] + if (!Number.isInteger(num)) { + error = "Number can't be empty"; + } else if (min > parseInt(num.toString())) { + error = `Number must be at least ${component.min}`; + } else if (max < parseInt(num.toString())) { + error = `Number can't be higher then ${component.max}`; } else { error = undefined; } @@ -72,7 +63,6 @@ min={min} max={max} bind:value={$activeResponses[id].data[component.id]} - on:blur={validateInput} class="bg-primary rounded-xl px-4 py-2 text-white remove-arrow focus:drop-shadow-btn-hover min-w-9" />