Forms
A guide to building forms with Vase UI components.
Vase UI form control components extend the native constraint validation API. You can build forms that collect user input or give control over an interface. The components also work with form libraries such as VeeValidate and TanStack Form.
The demos on this page use Tailwind CSS, and the files in components give each part its classes. The VeeValidate and TanStack Form demos use the same files.
<script setup lang="ts">
import { ToastProvider } from '../../components/toast';
import ExampleForm from './ExampleForm.vue';
</script>
<template>
<ToastProvider aria-label="Form notifications">
<ExampleForm />
</ToastProvider>
</template><script setup lang="ts">
import { h } from 'vue';
import type { FunctionalComponent } from 'vue';
import * as Autocomplete from '../../components/autocomplete';
import { Button } from '../../components/button';
import { Checkbox } from '../../components/checkbox';
import { CheckboxGroup } from '../../components/checkbox-group';
import * as Combobox from '../../components/combobox';
import * as Field from '../../components/field';
import * as Fieldset from '../../components/fieldset';
import { Input } from '../../components/input';
import { Form } from '../../components/form';
import * as NumberField from '../../components/number-field';
import { Radio } from '../../components/radio';
import { RadioGroup } from '../../components/radio-group';
import * as Select from '../../components/select';
import * as Slider from '../../components/slider';
import { Switch } from '../../components/switch';
import { useToastManager } from '../../components/toast';
const toastManager = useToastManager();
function onSubmit(_event: SubmitEvent, formValues: Record<string, unknown>) {
toastManager.add({
title: 'Form submitted',
description: 'The form contains these values:',
data: formValues,
});
}
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
const CaretUpDownIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'currentColor', ...attrs }, [
h('path', { d: 'M11 10H5l3 3.5zm0-4H5l3-3.5z' }),
]);
const CheckIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'none', stroke: 'currentColor', ...attrs }, [
h('path', { d: 'm2.5 8.5 4 4 7-9' }),
]);
const PlusIcon: FunctionalComponent = (_, { attrs }) =>
h(
'svg',
{
...ICON_PROPS,
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
...attrs,
},
[h('path', { d: 'M1.5 8h13M8 14.5v-13' })],
);
const MinusIcon: FunctionalComponent = (_, { attrs }) =>
h(
'svg',
{
...ICON_PROPS,
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
...attrs,
},
[h('path', { d: 'M1.5 8h13' })],
);
function cartesian(...arrays: string[][]): string[][] {
return arrays.reduce<string[][]>(
(acc, curr) => acc.flatMap((a) => curr.map((b) => [...a, b])),
[[]],
);
}
const REGIONS = cartesian(['us', 'eu', 'ap'], ['central', 'east', 'west'], ['1', '2', '3']).map(
(part) => part.join('-'),
);
interface Image {
url: string;
name: string;
}
const IMAGES: Image[] = [
'nginx:1.29-alpine',
'node:22-slim',
'postgres:18',
'redis:8.2.2-alpine',
].map((name) => ({ url: `docker.io/library/${name}`, name }));
const SERVER_TYPES = [
{ label: 'Select server type', value: null },
...cartesian(['t', 'm'], ['1', '2'], ['small', 'medium', 'large']).map((part) => {
const value = part.join('.').replace('.', '');
return { label: value, value };
}),
];
const protocols = ['http', 'https', 'ssh'];
const popupHiddenClass = 'scale-[0.98] opacity-0';
</script>
<template>
<Form aria-label="Launch new cloud server" @submit="onSubmit">
<Field.Root name="serverName">
<Field.Label>Server name</Field.Label>
<Input
default-value=""
placeholder="e.g. api-server-01"
required
:minlength="3"
pattern=".*[A-Za-z].*"
/>
<Field.Description>Must be 3 or more characters long</Field.Description>
<Field.Error />
</Field.Root>
<Field.Root name="region">
<Combobox.Root :items="REGIONS" required>
<div class="relative text-sm leading-5 font-bold text-neutral-950 dark:text-white">
<Field.Label class="mb-1 block">Region</Field.Label>
<Combobox.InputGroup>
<Combobox.Input placeholder="e.g. eu-central-1" />
<div
class="absolute right-0 bottom-0 inline-flex h-full items-center justify-center text-neutral-500 dark:text-neutral-400"
>
<Combobox.Clear />
<Combobox.Trigger>
<Combobox.CaretDownIcon />
</Combobox.Trigger>
</div>
</Combobox.InputGroup>
</div>
<Combobox.Portal>
<Combobox.Positioner>
<Combobox.Popup>
<Combobox.Empty>No matches</Combobox.Empty>
<Combobox.List>
<template #item="{ item }">
<Combobox.Item v-slot="{ state }" :value="item">
<span v-if="state.selected" class="col-start-1">
<CheckIcon />
</span>
<span class="col-start-2">{{ item }}</span>
</Combobox.Item>
</template>
</Combobox.List>
</Combobox.Popup>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
<Field.Error />
</Field.Root>
<Field.Root name="containerImage">
<Autocomplete.Root
:items="IMAGES"
mode="both"
:item-to-string-value="(itemValue: Image) => itemValue.url"
required
>
<Field.Label>Container image</Field.Label>
<Autocomplete.Input placeholder="e.g. docker.io/library/node:latest" />
<Field.Description>Enter a registry URL with optional tags</Field.Description>
<Autocomplete.Portal>
<Autocomplete.Positioner>
<Autocomplete.Popup>
<Autocomplete.List>
<template #item="{ item }">
<Autocomplete.Item :value="item">
<span>{{ item.name }}</span>
<span class="font-mono whitespace-nowrap text-xs opacity-80">
{{ item.url }}
</span>
</Autocomplete.Item>
</template>
</Autocomplete.List>
</Autocomplete.Popup>
</Autocomplete.Positioner>
</Autocomplete.Portal>
</Autocomplete.Root>
<Field.Error />
</Field.Root>
<Field.Root name="serverType">
<Select.Root :items="SERVER_TYPES" required>
<div class="w-fit space-y-1">
<Select.Label>Server type</Select.Label>
<Select.Trigger class="w-48">
<Select.Value />
<Select.Icon>
<CaretUpDownIcon />
</Select.Icon>
</Select.Trigger>
</div>
<Select.Portal>
<Select.Positioner>
<Transition :enter-from-class="popupHiddenClass" :leave-to-class="popupHiddenClass">
<Select.Popup>
<Select.ScrollUpArrow />
<Select.List>
<Select.Item
v-for="{ label, value } in SERVER_TYPES"
:key="label"
:value="value"
v-slot="{ state }"
>
<span v-if="state.selected" class="col-start-1">
<CheckIcon />
</span>
<Select.ItemText>{{ label }}</Select.ItemText>
</Select.Item>
</Select.List>
<Select.ScrollDownArrow />
</Select.Popup>
</Transition>
</Select.Positioner>
</Select.Portal>
</Select.Root>
<Field.Error />
</Field.Root>
<Field.Root name="numOfInstances">
<NumberField.Root :min="1" :max="64" required>
<Field.Label>Number of instances</Field.Label>
<NumberField.Group>
<NumberField.Decrement aria-label="Decrease">
<MinusIcon />
</NumberField.Decrement>
<NumberField.Input />
<NumberField.Increment aria-label="Increase">
<PlusIcon />
</NumberField.Increment>
</NumberField.Group>
</NumberField.Root>
<Field.Error />
</Field.Root>
<Field.Root name="scalingThreshold">
<Fieldset.Root>
<template #element="{ props, elementRef }">
<Slider.Root
v-bind="props"
:ref="elementRef"
:default-value="[0.2, 0.8]"
thumb-alignment="edge"
:min="0"
:max="1"
:step="0.01"
:format="{ style: 'percent', minimumFractionDigits: 0, maximumFractionDigits: 0 }"
class="w-full gap-y-2"
>
<Fieldset.Legend>Scaling threshold</Fieldset.Legend>
<Slider.Value class="col-start-2 text-end" />
<Slider.Control>
<Slider.Track>
<Slider.Indicator />
<Slider.Thumb :index="0" aria-label="Minimum threshold" />
<Slider.Thumb :index="1" aria-label="Maximum threshold" />
</Slider.Track>
</Slider.Control>
</Slider.Root>
</template>
</Fieldset.Root>
</Field.Root>
<Field.Root name="storageType">
<Fieldset.Root>
<template #element="{ props, elementRef }">
<RadioGroup v-bind="props" :ref="elementRef" class="gap-4" default-value="ssd">
<Fieldset.Legend class="-mt-px">Storage type</Fieldset.Legend>
<Field.Item>
<Field.Label>
<Radio value="ssd" />
SSD
</Field.Label>
</Field.Item>
<Field.Item>
<Field.Label>
<Radio value="hdd" />
HDD
</Field.Label>
</Field.Item>
</RadioGroup>
</template>
</Fieldset.Root>
</Field.Root>
<Field.Root name="restartOnFailure">
<Field.Label class="gap-2">
Restart on failure
<span class="relative flex shrink-0"
><Switch default-checked /><span
class="pointer-events-none absolute top-[0.1875rem] left-[0.1875rem] size-3.5 bg-neutral-950 transition-[translate,background-color] duration-150 ease-[ease] peer-checked:translate-x-4 peer-checked:bg-white dark:bg-white dark:peer-checked:bg-neutral-950"
/></span>
</Field.Label>
</Field.Root>
<Field.Root name="allowedNetworkProtocols">
<Fieldset.Root>
<template #element="{ props, elementRef }">
<CheckboxGroup v-bind="props" :ref="elementRef" :default-value="[]">
<Fieldset.Legend class="mb-2">Allowed network protocols</Fieldset.Legend>
<div class="flex gap-4">
<Field.Item v-for="protocol in protocols" :key="protocol">
<Field.Label class="uppercase">
<span class="relative flex shrink-0"
><Checkbox :value="protocol" /><CheckIcon
class="pointer-events-none absolute inset-0 hidden text-white peer-checked:block dark:text-neutral-950"
/></span>
{{ protocol }}
</Field.Label>
</Field.Item>
</div>
</CheckboxGroup>
</template>
</Fieldset.Root>
</Field.Root>
<Button type="submit" class="mt-3">Launch server</Button>
</Form>
</template>import { Autocomplete } from '@vase-ui/vue/autocomplete';
import { withProps } from './withProps';
export const Root = Autocomplete.Root;
export const Input = withProps(Autocomplete.Input, {
class:
'h-8 w-[16rem] border border-neutral-950 bg-white px-2 text-sm any-pointer-coarse:text-base font-normal text-neutral-950 placeholder:text-neutral-500 focus:outline-2 focus:-outline-offset-1 focus:outline-neutral-950 dark:focus:outline-white md:w-[20rem] dark:border-white dark:bg-neutral-950 dark:text-white dark:placeholder:text-neutral-400',
});
export const Portal = Autocomplete.Portal;
export const Positioner = withProps(Autocomplete.Positioner, {
class: 'outline-none data-empty:hidden',
sideOffset: 4,
});
export const Popup = withProps(Autocomplete.Popup, {
class:
'w-(--anchor-width) max-w-(--available-width) border border-neutral-950 bg-white text-neutral-950 shadow-[0.25rem_0.25rem_0] shadow-black/12 dark:border-white dark:bg-neutral-950 dark:text-white dark:shadow-none',
});
export const List = withProps(Autocomplete.List, {
class:
'max-h-[min(22.5rem,var(--available-height))] overflow-y-auto overscroll-contain py-1 scroll-py-1 outline-0 data-empty:p-0',
});
export const Item = withProps(Autocomplete.Item, {
class:
'flex cursor-default flex-col gap-0.25 py-2 pr-8 pl-2 text-sm leading-4 outline-none select-none data-highlighted:relative data-highlighted:z-0 data-highlighted:text-white data-highlighted:before:absolute data-highlighted:before:inset-0 data-highlighted:before:z-[-1] data-highlighted:before:bg-neutral-950 dark:data-highlighted:text-neutral-950 dark:data-highlighted:before:bg-white',
});import { Button as VaseButton } from '@vase-ui/vue/button';
import { withProps } from './withProps';
export const Button = withProps(VaseButton, {
type: 'button',
class:
'flex h-8 items-center justify-center gap-2 rounded-none border border-neutral-950 bg-white px-3 py-0 font-[inherit] text-sm leading-none whitespace-nowrap font-normal text-neutral-950 select-none hover:not-disabled:not-aria-disabled:bg-neutral-100 active:not-disabled:not-aria-disabled:bg-neutral-200 aria-disabled:border-neutral-500 aria-disabled:text-neutral-500 disabled:border-neutral-500 disabled:text-neutral-500 focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-neutral-950 dark:focus-visible:outline-white dark:border-white dark:bg-neutral-950 dark:text-white dark:hover:not-disabled:not-aria-disabled:bg-neutral-800 dark:active:not-disabled:not-aria-disabled:bg-neutral-700 dark:aria-disabled:border-neutral-400 dark:aria-disabled:text-neutral-400 dark:disabled:border-neutral-400 dark:disabled:text-neutral-400',
});import { CheckboxGroup as VaseCheckboxGroup } from '@vase-ui/vue/checkbox-group';
import { withProps } from './withProps';
export const CheckboxGroup = withProps(VaseCheckboxGroup, {
class: 'flex flex-col items-start gap-1 text-neutral-950 dark:text-white',
});import { Checkbox as CheckboxBase } from '@vase-ui/vue/checkbox';
import { withProps } from './withProps';
// The mark is an element beside the checkbox. `peer-checked` shows it.
export const Checkbox = withProps(CheckboxBase, {
class:
'peer m-0 size-4 shrink-0 appearance-none rounded-none border border-neutral-950 bg-white p-0 checked:bg-neutral-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-950 dark:focus-visible:outline-white dark:border-white dark:bg-neutral-950 dark:checked:bg-white',
});import { h, mergeProps, Transition } from 'vue';
import type { FunctionalComponent } from 'vue';
import { Combobox } from '@vase-ui/vue/combobox';
import { withProps } from './withProps';
export const Root = Combobox.Root;
export const Input = withProps(Combobox.Input, {
class:
'h-full w-full border-0 bg-white pl-2 text-sm any-pointer-coarse:text-base font-normal text-neutral-950 outline-none placeholder:text-neutral-500 dark:bg-neutral-950 dark:text-white dark:placeholder:text-neutral-400',
});
export const InputGroup = withProps(Combobox.InputGroup, {
class:
'relative h-8 w-64 border border-neutral-950 bg-white focus-within:outline-2 focus-within:-outline-offset-1 focus-within:outline-neutral-950 dark:focus-within:outline-white dark:border-white dark:bg-neutral-950 [&>input]:pr-[2.5rem] has-[.combobox-clear]:[&>input]:pr-[calc(0.5rem+2rem*2)]',
});
const ClearWrapper: FunctionalComponent = (_, { attrs, slots }) =>
h(
Combobox.Clear,
mergeProps(
{
'aria-label': 'Clear selection',
class:
'combobox-clear flex h-full w-6 items-center justify-center border-0 bg-transparent p-0 text-neutral-950 dark:text-white',
},
attrs,
),
{ ...slots, default: () => h(XIcon) },
);
ClearWrapper.inheritAttrs = false;
export const Clear = ClearWrapper as unknown as typeof Combobox.Clear;
export const Trigger = withProps(Combobox.Trigger, {
class:
'flex h-full w-6 items-center justify-center border-0 bg-transparent p-0 text-neutral-950 dark:text-white',
});
export const Portal = Combobox.Portal;
export const Positioner = withProps(Combobox.Positioner, { class: 'outline-none', sideOffset: 4 });
// The enter-from and leave-to class of the `<Transition>` around the popup.
const POPUP_HIDDEN = 'scale-95 opacity-0';
const PopupWrapper: FunctionalComponent = (_, { attrs, slots }) =>
h(Transition, { enterFromClass: POPUP_HIDDEN, leaveToClass: POPUP_HIDDEN, appear: true }, () =>
h(
Combobox.Popup,
mergeProps(
{
class:
'w-(--anchor-width) max-w-(--available-width) origin-(--transform-origin) border border-neutral-950 bg-white text-neutral-950 shadow-[0.25rem_0.25rem_0_rgb(0_0_0/12%)] transition-[scale,opacity] duration-100 dark:border-white dark:bg-neutral-950 dark:text-white dark:shadow-none',
},
attrs,
),
slots,
),
);
PopupWrapper.inheritAttrs = false;
export const Popup = PopupWrapper as unknown as typeof Combobox.Popup;
const EmptyWrapper: FunctionalComponent = (_, { attrs, slots }) => {
const { class: className, ...props } = attrs;
return h(Combobox.Empty, props, {
...slots,
default: () =>
slots.default
? h(
'div',
{
class: [
'py-4 pr-4 pl-2 text-sm leading-4 text-neutral-500 dark:text-neutral-400',
className,
],
},
slots.default(),
)
: null,
});
};
EmptyWrapper.inheritAttrs = false;
export const Empty = EmptyWrapper as unknown as typeof Combobox.Empty;
export const List = withProps(Combobox.List, {
class:
'outline-0 overflow-y-auto scroll-py-[0.25rem] py-1 overscroll-contain max-h-[min(22.5rem,var(--available-height))] data-empty:p-0',
});
export const Item = withProps(Combobox.Item, {
class:
'grid cursor-default grid-cols-[1rem_1fr] items-center gap-2 p-2 text-sm leading-4 outline-none select-none data-highlighted:relative data-highlighted:z-0 data-highlighted:text-white data-highlighted:before:absolute data-highlighted:before:inset-0 data-highlighted:before:z-[-1] data-highlighted:before:bg-neutral-950 dark:data-highlighted:text-neutral-950 dark:data-highlighted:before:bg-white',
});
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
export const CaretDownIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', mergeProps({ ...ICON_PROPS, fill: 'currentColor' }, attrs), [
h('path', { d: 'M12 6H4l4 4.5z' }),
]);
CaretDownIcon.inheritAttrs = false;
const XIcon: FunctionalComponent = () =>
h(
'svg',
{
...ICON_PROPS,
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
},
[h('path', { d: 'm4.5 4.5 7 7m-7 0 7-7' })],
);import { Field } from '@vase-ui/vue/field';
import { withProps } from './withProps';
export const Root = withProps(Field.Root, { class: 'flex flex-col items-start gap-1' });
export const Label = withProps(Field.Label, {
class:
'text-sm font-bold text-neutral-950 has-[[type=checkbox]]:flex has-[[type=checkbox]]:items-center has-[[type=checkbox]]:gap-2 has-[[type=checkbox]]:font-normal has-[[type=radio]]:flex has-[[type=radio]]:items-center has-[[type=radio]]:gap-2 has-[[type=radio]]:font-normal dark:text-white',
});
export const Description = withProps(Field.Description, {
class: 'text-sm text-neutral-600 dark:text-neutral-400',
});
export const Error = withProps(Field.Error, { class: 'text-sm text-red-700 dark:text-red-400' });
export const Item = Field.Item;import { Fieldset } from '@vase-ui/vue/fieldset';
import { withProps } from './withProps';
export const Root = Fieldset.Root;
export const Legend = withProps(Fieldset.Legend, {
class: 'text-sm font-bold text-neutral-950 dark:text-white',
});import { Form as VaseForm } from '@vase-ui/vue/form';
import { withProps } from './withProps';
export const Form = withProps(VaseForm, {
class: 'flex w-full max-w-3xs flex-col gap-5 sm:max-w-[20rem]',
});import { Input as InputBase } from '@vase-ui/vue/input';
import { withProps } from './withProps';
export const Input = withProps(InputBase, {
class:
'h-8 w-full max-w-xs border border-neutral-950 bg-white px-2 text-sm any-pointer-coarse:text-base font-normal text-neutral-950 placeholder:text-neutral-500 focus:outline-2 focus:-outline-offset-1 focus:outline-neutral-950 dark:focus:outline-white dark:border-white dark:bg-neutral-950 dark:text-white dark:placeholder:text-neutral-400',
});import { NumberField } from '@vase-ui/vue/number-field';
import { withProps } from './withProps';
export const Root = withProps(NumberField.Root, { class: 'flex flex-col items-start gap-1' });
export const Group = withProps(NumberField.Group, { class: 'flex h-8' });
export const Decrement = withProps(NumberField.Decrement, {
class:
'flex h-full w-8 items-center justify-center rounded-none border border-neutral-950 bg-white bg-clip-padding text-neutral-950 outline-0 select-none hover:not-disabled:bg-neutral-100 active:not-disabled:bg-neutral-200 disabled:border-neutral-500 disabled:text-neutral-500 focus-visible:z-1 focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-neutral-950 dark:focus-visible:outline-white dark:border-white dark:bg-neutral-950 dark:text-white dark:hover:not-disabled:bg-neutral-800 dark:active:not-disabled:bg-neutral-700 dark:disabled:border-neutral-400 dark:disabled:text-neutral-400',
});
export const Input = withProps(NumberField.Input, {
class:
'h-full w-16 rounded-none border-y border-neutral-950 bg-white px-2 text-sm any-pointer-coarse:text-base font-normal text-neutral-950 tabular-nums focus:z-1 focus:outline-2 focus:-outline-offset-1 focus:outline-neutral-950 dark:focus:outline-white dark:border-white dark:bg-neutral-950 dark:text-white',
});
export const Increment = withProps(NumberField.Increment, {
class:
'flex h-full w-8 items-center justify-center rounded-none border border-neutral-950 bg-white bg-clip-padding text-neutral-950 outline-0 select-none hover:not-disabled:bg-neutral-100 active:not-disabled:bg-neutral-200 disabled:border-neutral-500 disabled:text-neutral-500 focus-visible:z-1 focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-neutral-950 dark:focus-visible:outline-white dark:border-white dark:bg-neutral-950 dark:text-white dark:hover:not-disabled:bg-neutral-800 dark:active:not-disabled:bg-neutral-700 dark:disabled:border-neutral-400 dark:disabled:text-neutral-400',
});import { RadioGroup as VaseRadioGroup } from '@vase-ui/vue/radio-group';
import { withProps } from './withProps';
export const RadioGroup = withProps(VaseRadioGroup, {
class: 'flex w-full flex-row items-start gap-1 text-neutral-950 dark:text-white',
});import { Radio as RadioBase } from '@vase-ui/vue/radio';
import { withProps } from './withProps';
// An inner ring leaves a dot in the middle of a checked radio.
export const Radio = withProps(RadioBase, {
class:
'm-0 size-4 shrink-0 appearance-none rounded-full border border-neutral-950 bg-white p-0 checked:bg-neutral-950 checked:shadow-[inset_0_0_0_0.1875rem_white] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-950 dark:focus-visible:outline-white dark:border-white dark:bg-neutral-950 dark:checked:bg-white dark:checked:shadow-[inset_0_0_0_0.1875rem_var(--color-neutral-950)]',
});import { Select } from '@vase-ui/vue/select';
import { withProps } from './withProps';
export const Root = Select.Root;
export const Label = withProps(Select.Label, {
class: 'cursor-default text-sm font-bold text-neutral-950 dark:text-white',
});
export const Trigger = withProps(Select.Trigger, {
class:
'flex h-8 min-w-40 cursor-default items-center justify-between gap-3 border border-neutral-950 bg-white pl-2 pr-1 text-sm font-normal text-neutral-950 select-none hover:enabled:bg-neutral-100 active:enabled:bg-neutral-200 disabled:border-neutral-500 disabled:text-neutral-500 data-pressed:bg-neutral-100 focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-neutral-950 dark:focus-visible:outline-white dark:border-white dark:bg-neutral-950 dark:text-white dark:hover:enabled:bg-neutral-800 dark:active:enabled:bg-neutral-700 dark:disabled:border-neutral-400 dark:disabled:text-neutral-400 dark:data-pressed:bg-neutral-800',
});
export const Value = withProps(Select.Value, {
class: 'data-placeholder:text-neutral-500 dark:data-placeholder:text-neutral-400',
});
export const Icon = Select.Icon;
export const Portal = Select.Portal;
export const Positioner = withProps(Select.Positioner, {
class: 'outline-none select-none z-10',
sideOffset: 4,
});
export const Popup = withProps(Select.Popup, {
class:
'group min-w-(--anchor-width) origin-(--transform-origin) border border-neutral-950 bg-white bg-clip-padding text-neutral-950 shadow-[0.25rem_0.25rem_0] shadow-black/12 transition-[scale,opacity] duration-100 ease-out data-[side=none]:min-w-[calc(var(--anchor-width)+1.75rem)] data-[side=none]:translate-y-px data-[side=none]:scale-100 data-[side=none]:opacity-100 data-[side=none]:transition-none dark:border-white dark:bg-neutral-950 dark:text-white dark:shadow-none',
});
export const ScrollUpArrow = withProps(Select.ScrollUpArrow, {
class:
"top-0 z-1 flex h-4 w-full cursor-default items-center justify-center bg-white text-center text-xs before:absolute data-[side=none]:before:-top-full before:left-0 before:h-full before:w-full before:content-[''] dark:bg-neutral-950",
});
export const ScrollDownArrow = withProps(Select.ScrollDownArrow, {
class:
"bottom-0 z-1 flex h-4 w-full cursor-default items-center justify-center bg-white text-center text-xs before:absolute before:left-0 before:h-full before:w-full before:content-[''] data-[side=none]:before:-bottom-full dark:bg-neutral-950",
});
export const List = withProps(Select.List, {
class: 'relative max-h-(--available-height) overflow-y-auto py-1 scroll-py-6',
});
export const Item = withProps(Select.Item, {
class:
'grid cursor-default grid-cols-[1rem_1fr] items-center gap-2 py-1.5 pr-4 pl-2.5 text-sm outline-none select-none group-data-[side=none]:pr-12 data-highlighted:bg-neutral-950 data-highlighted:text-white dark:data-highlighted:bg-white dark:data-highlighted:text-neutral-950',
});
export const ItemText = withProps(Select.ItemText, { class: 'col-start-2' });import { Slider } from '@vase-ui/vue/slider';
import { withProps } from './withProps';
export const Root = withProps(Slider.Root, { class: 'grid grid-cols-2' });
export const Value = withProps(Slider.Value, {
class: 'text-sm font-normal text-neutral-950 dark:text-white',
});
export const Control = withProps(Slider.Control, {
class: 'flex col-span-2 touch-none items-center py-3 select-none',
});
export const Track = withProps(Slider.Track, {
class: 'h-1 w-full bg-neutral-200 select-none dark:bg-neutral-800',
});
export const Indicator = withProps(Slider.Indicator, {
class: 'bg-neutral-950 select-none dark:bg-white',
});
export const Thumb = withProps(Slider.Thumb, {
class:
'size-4 border border-neutral-950 bg-white select-none has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-neutral-950 dark:has-[:focus-visible]:outline-white dark:border-white dark:bg-neutral-950',
});import { Switch as SwitchBase } from '@vase-ui/vue/switch';
import { withProps } from './withProps';
// The thumb is an element beside the switch. `peer-checked` moves it.
export const Switch = withProps(SwitchBase, {
class:
'peer m-0 h-5 w-9 shrink-0 appearance-none rounded-none border border-neutral-950 bg-white transition-colors duration-150 ease-[ease] checked:bg-neutral-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-950 dark:focus-visible:outline-white dark:border-white dark:bg-neutral-950 dark:checked:bg-white',
});import { defineComponent, h, mergeProps, TransitionGroup } from 'vue';
import type { FunctionalComponent } from 'vue';
import { Toast } from '@vase-ui/vue/toast';
const Toasts = defineComponent(() => {
const { toasts } = Toast.useToastManager();
return () =>
h(TransitionGroup, { enterFromClass: 'toast-starting', leaveToClass: 'toast-ending' }, () =>
toasts.value.map((toast) =>
h(
Toast.Root,
{
key: toast.id,
toast,
class:
"[--gap:0.75rem] [--peek:0.75rem] [--scale:calc(max(0,1-(var(--toast-index)*0.1)))] [--shrink:calc(1-var(--scale))] [--height:var(--toast-frontmost-height,var(--toast-height))] [--offset-y:calc(var(--toast-offset-y)*-1+calc(var(--toast-index)*var(--gap)*-1)+var(--toast-swipe-movement-y))] absolute right-0 bottom-0 left-auto z-[calc(1000-var(--toast-index))] mr-0 w-full origin-bottom transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--peek))-(var(--shrink)*var(--height))))_scale(var(--scale))] border border-neutral-950 bg-white text-neutral-950 shadow-[0.25rem_0.25rem_0] shadow-black/12 select-none dark:border-white dark:bg-neutral-950 dark:text-white dark:shadow-none after:absolute after:top-full after:left-0 after:h-[calc(var(--gap)+1px)] after:w-full after:content-[''] [&.toast-ending]:opacity-0 inert:opacity-0 [&.toast-starting]:transform-[translateY(150%)] [&.toast-ending:not([inert]):not([data-swipe-direction])]:transform-[translateY(150%)] [&.toast-ending]:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+150%))] [&.toast-ending]:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-150%))_translateY(var(--offset-y))] [&.toast-ending]:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+150%))_translateY(var(--offset-y))] [&.toast-ending]:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-150%))] h-(--height) [transition:transform_0.5s_cubic-bezier(0.22,1,0.36,1),opacity_0.5s,height_0.15s]",
},
() =>
h(
Toast.Content,
{ class: 'h-full overflow-hidden p-3 transition-opacity duration-250' },
() => [
h(Toast.Title, { class: 'text-sm font-bold' }),
h(Toast.Description, { class: 'text-sm text-neutral-700 dark:text-neutral-300' }),
h(
'div',
{
class:
'mt-2 border border-neutral-950 p-2 text-xs select-text dark:border-white',
'data-vase-ui-swipe-ignore': '',
},
h('pre', { class: 'whitespace-pre-wrap' }, JSON.stringify(toast.data, null, 2)),
),
h(
Toast.Close,
{
class:
'absolute top-3 right-3 flex size-8 items-center justify-center border-0 bg-transparent p-0 text-neutral-950 hover:bg-neutral-100 active:bg-neutral-200 focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-neutral-950 dark:focus-visible:outline-white dark:text-white dark:hover:bg-neutral-800 dark:active:bg-neutral-700',
'aria-label': 'Close',
},
() => h(XIcon),
),
],
),
),
),
);
});
export const ToastProvider = defineComponent(
(_, { attrs, slots }) => {
return () =>
h(Toast.Provider, { limit: 1 }, () => [
slots.default?.(),
h(Toast.Portal, null, () =>
h(
Toast.Viewport,
mergeProps(
{
class:
'fixed z-10 top-auto right-[1rem] bottom-[1rem] mx-auto flex w-[250px] sm:right-[2rem] sm:bottom-[2rem] sm:w-[360px]',
},
attrs,
),
() => h(Toasts),
),
),
]);
},
{ inheritAttrs: false },
);
export const useToastManager = Toast.useToastManager;
const XIcon: FunctionalComponent = () =>
h(
'svg',
{
width: '16',
height: '16',
viewBox: '0 0 16 16',
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
style: { display: 'block' },
},
[h('path', { d: 'm2.5 2.5 11 11m-11 0 11-11' })],
);import { h, mergeProps } from 'vue';
import type { Component, FunctionalComponent } from 'vue';
/**
* Returns `part` with `props` set. An attribute of the caller wins over a prop of the same name.
* The class of the caller follows the class of `props`, and the styles merge. The slots go to the
* part as they are. A template ref on the wrapper gives the root element of the part, not its
* exposed values.
*
* The vnode that `h()` makes is outside a block of Vue. The part and each component in its slots
* thus render again each time the wrapper renders. Vue patches the same nodes and mounts none
* again.
*
* The compiler of Vue avoids these renders with `openBlock`, `createBlock` and patch flags. Do not
* copy that form: a wrong flag drops a slot.
*/
export function withProps<Part>(part: Part, props: Record<string, unknown>): Part {
const Wrapper: FunctionalComponent = (_, { attrs, slots }) =>
h(part as Component, mergeProps(props, attrs), slots);
Wrapper.inheritAttrs = false;
return Wrapper as Part;
}Naming form controls
A form control must have an accessible name, so that assistive technologies can recognize it. Use the label strategy below for each type of control.
Input controls
Use <Field.Label> or a native <label> to label these controls:
InputNumberFieldOTPField: a native<label>names the first input. See Labeling an OTP field.AutocompleteCombobox(input outside the popup)CheckboxRadioSwitch
You can label Checkbox, Radio and Switch implicitly. Put them inside <Field.Label>:
<script setup lang="ts">
import { Field } from '@vase-ui/vue/field';
import { Switch } from '@vase-ui/vue/switch';
</script>
<template>
<Field.Root>
<Field.Label>
<Switch />
Developer mode
</Field.Label>
<Field.Description>Enables extra tools for web developers</Field.Description>
</Field.Root>
</template>Trigger-based controls
Combobox(input inside the popup): use<Combobox.Label>. See Input inside popup.Select: use<Select.Label>. See Labeling a select.Slider: use<Slider.Label>. For a slider with more than one thumb, also give each<Slider.Thumb>anaria-label, to tell the thumbs apart. See Labeling a slider.
Fallback
If no visible label is rendered, give aria-label to the part that is the form control.
Describing the control
<Field.Description> gives the control an accessible description automatically:
<script setup lang="ts">
import { Field } from '@vase-ui/vue/field';
import { Form } from '@vase-ui/vue/form';
import { Select } from '@vase-ui/vue/select';
import { Slider } from '@vase-ui/vue/slider';
</script>
<template>
<Form>
<Field.Root>
<Select.Root>
<Select.Label>Time zone</Select.Label>
<Select.Trigger />
</Select.Root>
<Field.Description>Used for notifications and reminders</Field.Description>
</Field.Root>
<Field.Root>
<Slider.Root :default-value="50">
<Slider.Label>Zoom level</Slider.Label>
<Field.Description>Adjust the size of the user interface</Field.Description>
<Slider.Control>
<Slider.Track>
<Slider.Thumb />
</Slider.Track>
</Slider.Control>
</Slider.Root>
</Field.Root>
</Form>
</template>Labeling control groups
To label a group of controls, put the group in <Fieldset.Root>, and its label in <Fieldset.Legend>. The legend names the fieldset, and also a group in it that nothing else names. Examples are a range slider with more than one thumb and a section that combines several inputs:
<script setup lang="ts">
import { Field } from '@vase-ui/vue/field';
import { Fieldset } from '@vase-ui/vue/fieldset';
import { Form } from '@vase-ui/vue/form';
import { Slider } from '@vase-ui/vue/slider';
</script>
<template>
<Form>
<Field.Root>
<Fieldset.Root>
<Fieldset.Legend>Price range</Fieldset.Legend>
<Slider.Root :default-value="[25, 75]">
<Slider.Control>
<Slider.Track>
<Slider.Thumb aria-label="Minimum price" />
<Slider.Thumb aria-label="Maximum price" />
</Slider.Track>
</Slider.Control>
</Slider.Root>
</Fieldset.Root>
</Field.Root>
</Form>
</template>Put a checkbox group or a radio group in Fieldset.Root. Wrap each option in <Field.Item>. Each control then has its own label and description:
<script setup lang="ts">
import { Field } from '@vase-ui/vue/field';
import { Fieldset } from '@vase-ui/vue/fieldset';
import { Radio } from '@vase-ui/vue/radio';
import { RadioGroup } from '@vase-ui/vue/radio-group';
</script>
<template>
<Field.Root name="storage">
<Fieldset.Root>
<Fieldset.Legend>Storage type</Fieldset.Legend>
<RadioGroup>
<Field.Item>
<Radio value="ssd" />
<Field.Label>SSD</Field.Label>
</Field.Item>
<Field.Item>
<Radio value="hdd" />
<Field.Label>HDD</Field.Label>
</Field.Item>
</RadioGroup>
</Fieldset.Root>
</Field.Root>
</template><script setup lang="ts">
import { Checkbox } from '@vase-ui/vue/checkbox';
import { CheckboxGroup } from '@vase-ui/vue/checkbox-group';
import { Field } from '@vase-ui/vue/field';
import { Fieldset } from '@vase-ui/vue/fieldset';
</script>
<template>
<Field.Root name="schedule">
<Fieldset.Root>
<Fieldset.Legend>Backup schedule</Fieldset.Legend>
<CheckboxGroup>
<Field.Item>
<Checkbox value="daily" />
<Field.Label>Daily</Field.Label>
<Field.Description>Daily at 00:00</Field.Description>
</Field.Item>
<Field.Item>
<Checkbox value="monthly" />
<Field.Label>Monthly</Field.Label>
<Field.Description>On the 5th of every month at 23:59</Field.Description>
</Field.Item>
</CheckboxGroup>
</Fieldset.Root>
</Field.Root>
</template>Building form fields
Give name to <Field.Root> to include the value of the control that it wraps when a parent form is submitted:
<script setup lang="ts">
import { Combobox } from '@vase-ui/vue/combobox';
import { Field } from '@vase-ui/vue/field';
import { Form } from '@vase-ui/vue/form';
</script>
<template>
<Form>
<Field.Root name="country">
<Field.Label>Country of residence</Field.Label>
<Combobox.Root>
<Combobox.Input />
</Combobox.Root>
</Field.Root>
</Form>
</template>A control that a Teleport moves out of the form needs the form attribute with the id of the form.
Submitting data
Form emits submit only when each field is valid. The first argument is the native SubmitEvent. While Form has a submit listener, it prevents the native submit, so the page stays. Send the FormData of the form in the listener:
<script setup lang="ts">
import { useTemplateRef } from 'vue';
import { Form } from '@vase-ui/vue/form';
const form = useTemplateRef('form');
async function onSubmit() {
const formData = new FormData(form.value?.element ?? undefined);
await fetch('https://api.example.com', {
method: 'POST',
body: formData,
});
}
</script>
<template>
<Form ref="form" @submit="onSubmit" />
</template>The second argument has the values of the named fields of the form as an object. Each value has the type that its control gives:
<script setup lang="ts">
import { Form } from '@vase-ui/vue/form';
async function onSubmit(_event: SubmitEvent, formValues: Record<string, unknown>) {
const payload = {
product_id: formValues.id,
order_quantity: formValues.quantity,
};
await fetch('https://api.example.com', {
method: 'POST',
body: JSON.stringify(payload),
});
}
</script>
<template>
<Form @submit="onSubmit" />
</template>Constraint validation
Vase UI form components support the native HTML validation attributes for many validation rules:
requiredspecifies a required field.minlengthandmaxlengthspecify a valid length for text fields.patternspecifies a regular expression that the value of the field must match.stepspecifies an increment that the values of a numeric field must be an integral multiple of.
<script setup lang="ts">
import { Field } from '@vase-ui/vue/field';
import { Input } from '@vase-ui/vue/input';
</script>
<template>
<Field.Root name="website">
<Input type="url" required pattern="https?://.*" />
<Field.Error />
</Field.Root>
</template>Input, Checkbox, Radio and Switch render native inputs, so the browser shows their validation messages at the control. A component such as Select or NumberField takes part in native submission and validation with a visually hidden input. That input is in the element of the component, and it is position: absolute. Give the root of the component, or an element around it, position: relative. The native validation message then points at the control.
Custom validation
You can add custom validation logic with a synchronous or an asynchronous function in the validate prop. It runs after the native validations pass.
Use the validationMode prop to set when the validation runs:
submit(default) validates the fields when the parent<Form>is submitted. Afterward, the fields validate again when their value changes.blurvalidates the field when the focus moves away.changevalidates the field when its value changes. A key press in a text field is an example. So is a click on a checkbox.
validationDebounceTime sets, in milliseconds, how long to wait between validate calls in change mode. Use it for asynchronous requests and for text fields that validate on change.
validate gets the value of the field and the values of its form. An asynchronous validate function does not stop the submission of a form in submit mode.
<script setup lang="ts">
import { Field } from '@vase-ui/vue/field';
import { Input } from '@vase-ui/vue/input';
declare function isUsernameAvailable(username: string): Promise<boolean>;
async function validate(value: unknown) {
if (value === 'admin') {
return 'Reserved for system use.';
}
if (!(await isUsernameAvailable(String(value)))) {
return `${String(value)} is unavailable.`;
}
// Return `null` when the value is valid.
return null;
}
</script>
<template>
<Field.Root
name="username"
validation-mode="change"
:validation-debounce-time="300"
:validate="validate"
>
<Input required :minlength="3" />
<Field.Error />
</Field.Root>
</template>Server-side validation
Bind the errors that a server returns after a submission with v-model:errors of Form. The form gives them to each field for display.
errors is an object. Its keys are field names, and each value is an error string or an array of error strings. An edit of a field asks to remove the key of that field with update:errors. A native reset of the form asks to remove the key of each field.
<script setup lang="ts">
import { ref } from 'vue';
import { Field } from '@vase-ui/vue/field';
import { Input } from '@vase-ui/vue/input';
import { Form } from '@vase-ui/vue/form';
async function submitToServer() {
return {
errors: {
promoCode: 'This promo code has expired',
},
};
}
const errors = ref<Record<string, string | string[]>>();
async function onSubmit() {
const response = await submitToServer();
errors.value = response.errors;
}
</script>
<template>
<Form v-model:errors="errors" @submit="onSubmit">
<Field.Root name="promoCode">
<Input />
<Field.Error />
</Field.Root>
</Form>
</template>After a submit that passes the validation, the next change of errors moves the focus to the first field that has an error. An edit or a reset before that change cancels the move.
The demo Submit to a server of the Form page shows the errors of a server after a submission.
Displaying errors
Use <Field.Error> with no content to show the native error message of the field while it is invalid. The match prop customizes the message for a validity state, so that you can manage internationalization in your application:
<script setup lang="ts">
import { Field } from '@vase-ui/vue/field';
import { Input } from '@vase-ui/vue/input';
</script>
<template>
<Field.Root name="username">
<Input required />
<Field.Error match="valueMissing">You must create a username</Field.Error>
</Field.Root>
</template>VeeValidate
VeeValidate is a form library for Vue. You can integrate it with Vase UI to manage the form state and the field state outside the components.
<script setup lang="ts">
import { ToastProvider } from '../../components/toast';
import VeeValidateForm from './VeeValidateForm.vue';
</script>
<template>
<ToastProvider aria-label="VeeValidate notifications">
<VeeValidateForm />
</ToastProvider>
</template><script setup lang="ts">
import { Field as VeeField, useForm } from 'vee-validate';
import { h, useTemplateRef } from 'vue';
import type { FunctionalComponent } from 'vue';
import * as Autocomplete from '../../components/autocomplete';
import { Button } from '../../components/button';
import { Checkbox } from '../../components/checkbox';
import { CheckboxGroup } from '../../components/checkbox-group';
import * as Combobox from '../../components/combobox';
import * as Field from '../../components/field';
import * as Fieldset from '../../components/fieldset';
import { Input } from '../../components/input';
import * as NumberField from '../../components/number-field';
import { Radio } from '../../components/radio';
import { RadioGroup } from '../../components/radio-group';
import * as Select from '../../components/select';
import * as Slider from '../../components/slider';
import { Switch } from '../../components/switch';
import { useToastManager } from '../../components/toast';
interface FormValues {
serverName: string;
region: string | null;
containerImage: string;
serverType: string | null;
numOfInstances: number | null;
scalingThreshold: number[];
storageType: 'ssd' | 'hdd';
restartOnFailure: boolean;
allowedNetworkProtocols: string[];
}
const toastManager = useToastManager();
const { handleSubmit } = useForm<FormValues>({
initialValues: {
serverName: '',
region: null,
containerImage: '',
serverType: null,
numOfInstances: null,
scalingThreshold: [0.2, 0.8],
storageType: 'ssd',
restartOnFailure: true,
allowedNetworkProtocols: [],
},
});
function submitForm(data: FormValues) {
toastManager.add({
title: 'Form submitted',
description: 'The form contains these values:',
data,
});
}
const formElement = useTemplateRef('formElement');
// The element with the name of a field can be a hidden input of a part, which takes no focus. The
// input of a number field gives the focus to its control. A select gives it to its trigger, and a
// combobox to its text input.
const onSubmit = handleSubmit(submitForm, ({ errors }) => {
const [name] = Object.keys(errors);
const named = formElement.value?.querySelector<HTMLInputElement>(`[name="${name}"]`);
const target =
named?.type === 'hidden'
? named.parentElement?.querySelector<HTMLElement>(
'input:not([type="hidden"]), [role="combobox"]',
)
: named;
target?.focus();
});
function required(value: unknown) {
return value === null || value === '' ? 'This field is required.' : true;
}
function validateServerName(value: unknown) {
if (typeof value !== 'string' || value === '') {
return 'This field is required.';
}
return value.length < 3 ? 'At least 3 characters.' : true;
}
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
const CaretUpDownIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'currentColor', ...attrs }, [
h('path', { d: 'M11 10H5l3 3.5zm0-4H5l3-3.5z' }),
]);
const CheckIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'none', stroke: 'currentColor', ...attrs }, [
h('path', { d: 'm2.5 8.5 4 4 7-9' }),
]);
const PlusIcon: FunctionalComponent = (_, { attrs }) =>
h(
'svg',
{
...ICON_PROPS,
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
...attrs,
},
[h('path', { d: 'M1.5 8h13M8 14.5v-13' })],
);
const MinusIcon: FunctionalComponent = (_, { attrs }) =>
h(
'svg',
{
...ICON_PROPS,
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
...attrs,
},
[h('path', { d: 'M1.5 8h13' })],
);
function cartesian(...arrays: string[][]): string[][] {
return arrays.reduce<string[][]>(
(acc, curr) => acc.flatMap((a) => curr.map((b) => [...a, b])),
[[]],
);
}
const REGIONS = cartesian(['us', 'eu', 'ap'], ['central', 'east', 'west'], ['1', '2', '3']).map(
(part) => part.join('-'),
);
interface Image {
url: string;
name: string;
}
const IMAGES: Image[] = [
'nginx:1.29-alpine',
'node:22-slim',
'postgres:18',
'redis:8.2.2-alpine',
].map((name) => ({ url: `docker.io/library/${name}`, name }));
const SERVER_TYPES = [
{ label: 'Select server type', value: null },
...cartesian(['t', 'm'], ['1', '2'], ['small', 'medium', 'large']).map((part) => {
const value = part.join('.').replace('.', '');
return { label: value, value };
}),
];
const protocols = ['http', 'https', 'ssh'];
// The input of a slider thumb has the focus, and `blur` does not bubble. The thumbs thus listen
// to `focusout`.
const popupHiddenClass = 'scale-[0.98] opacity-0';
</script>
<template>
<form
ref="formElement"
aria-label="Launch new cloud server with VeeValidate"
novalidate
class="flex w-full max-w-3xs flex-col gap-5 sm:max-w-[20rem]"
@submit="onSubmit"
>
<VeeField
v-slot="{ componentField, meta, errorMessage }"
name="serverName"
:rules="validateServerName"
>
<Field.Root
:name="componentField.name"
:invalid="!!errorMessage"
:dirty="meta.dirty"
:touched="meta.touched"
>
<Field.Label>Server name</Field.Label>
<Input
placeholder="e.g. api-server-01"
:model-value="componentField.modelValue"
@update:model-value="componentField['onUpdate:modelValue']"
@blur="componentField.onBlur"
/>
<Field.Description>Must be 3 or more characters long</Field.Description>
<Field.Error>
{{ errorMessage }}
</Field.Error>
</Field.Root>
</VeeField>
<VeeField
v-slot="{ field, value, meta, errorMessage, handleChange, handleBlur }"
name="region"
:rules="required"
>
<Field.Root
:name="field.name"
:invalid="!!errorMessage"
:dirty="meta.dirty"
:touched="meta.touched"
>
<Combobox.Root :items="REGIONS" :model-value="value" @update:model-value="handleChange">
<div class="relative text-sm leading-5 font-bold text-neutral-950 dark:text-white">
<Field.Label class="mb-1 block">Region</Field.Label>
<Combobox.InputGroup>
<Combobox.Input placeholder="e.g. eu-central-1" @blur="handleBlur" />
<div
class="absolute right-0 bottom-0 inline-flex h-full items-center justify-center text-neutral-500 dark:text-neutral-400"
>
<Combobox.Clear />
<Combobox.Trigger>
<Combobox.CaretDownIcon />
</Combobox.Trigger>
</div>
</Combobox.InputGroup>
</div>
<Combobox.Portal>
<Combobox.Positioner>
<Combobox.Popup>
<Combobox.Empty>No matches</Combobox.Empty>
<Combobox.List>
<template #item="{ item }">
<Combobox.Item v-slot="{ state }" :value="item">
<span v-if="state.selected" class="col-start-1">
<CheckIcon />
</span>
<span class="col-start-2">{{ item }}</span>
</Combobox.Item>
</template>
</Combobox.List>
</Combobox.Popup>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
<Field.Error>
{{ errorMessage }}
</Field.Error>
</Field.Root>
</VeeField>
<VeeField
v-slot="{ field, value, meta, errorMessage, handleChange, handleBlur }"
name="containerImage"
:rules="required"
>
<Field.Root
:name="field.name"
:invalid="!!errorMessage"
:dirty="meta.dirty"
:touched="meta.touched"
>
<Autocomplete.Root
:items="IMAGES"
mode="both"
:model-value="value"
:item-to-string-value="(itemValue: Image) => itemValue.url"
@update:model-value="handleChange"
>
<Field.Label>Container image</Field.Label>
<Autocomplete.Input placeholder="e.g. docker.io/library/node:latest" @blur="handleBlur" />
<Field.Description>Enter a registry URL with optional tags</Field.Description>
<Autocomplete.Portal>
<Autocomplete.Positioner>
<Autocomplete.Popup>
<Autocomplete.List>
<template #item="{ item }">
<Autocomplete.Item :value="item">
<span>{{ item.name }}</span>
<span class="font-mono whitespace-nowrap text-xs opacity-80">{{
item.url
}}</span>
</Autocomplete.Item>
</template>
</Autocomplete.List>
</Autocomplete.Popup>
</Autocomplete.Positioner>
</Autocomplete.Portal>
</Autocomplete.Root>
<Field.Error>
{{ errorMessage }}
</Field.Error>
</Field.Root>
</VeeField>
<VeeField
v-slot="{ field, value, meta, errorMessage, handleChange, handleBlur }"
name="serverType"
:rules="required"
>
<Field.Root
:name="field.name"
:invalid="!!errorMessage"
:dirty="meta.dirty"
:touched="meta.touched"
>
<Select.Root :items="SERVER_TYPES" :model-value="value" @update:model-value="handleChange">
<div class="w-fit space-y-1">
<Select.Label>Server type</Select.Label>
<Select.Trigger class="w-48" @blur="handleBlur">
<Select.Value />
<Select.Icon>
<CaretUpDownIcon />
</Select.Icon>
</Select.Trigger>
</div>
<Select.Portal>
<Select.Positioner>
<Transition :enter-from-class="popupHiddenClass" :leave-to-class="popupHiddenClass">
<Select.Popup>
<Select.ScrollUpArrow />
<Select.List>
<Select.Item
v-for="{ label, value: serverType } in SERVER_TYPES"
:key="label"
:value="serverType"
v-slot="{ state }"
>
<span v-if="state.selected" class="col-start-1">
<CheckIcon />
</span>
<Select.ItemText>{{ label }}</Select.ItemText>
</Select.Item>
</Select.List>
<Select.ScrollDownArrow />
</Select.Popup>
</Transition>
</Select.Positioner>
</Select.Portal>
</Select.Root>
<Field.Error>
{{ errorMessage }}
</Field.Error>
</Field.Root>
</VeeField>
<VeeField
v-slot="{ field, value, meta, errorMessage, handleChange, handleBlur }"
name="numOfInstances"
:rules="required"
>
<Field.Root
:name="field.name"
:invalid="!!errorMessage"
:dirty="meta.dirty"
:touched="meta.touched"
>
<NumberField.Root
:model-value="value"
:min="1"
:max="64"
@update:model-value="handleChange"
>
<Field.Label>Number of instances</Field.Label>
<NumberField.Group>
<NumberField.Decrement aria-label="Decrease">
<MinusIcon />
</NumberField.Decrement>
<NumberField.Input @blur="handleBlur" />
<NumberField.Increment aria-label="Increase">
<PlusIcon />
</NumberField.Increment>
</NumberField.Group>
</NumberField.Root>
<Field.Error>
{{ errorMessage }}
</Field.Error>
</Field.Root>
</VeeField>
<VeeField
v-slot="{ field, value, meta, errorMessage, handleChange, handleBlur }"
name="scalingThreshold"
>
<Field.Root
:name="field.name"
:invalid="!!errorMessage"
:dirty="meta.dirty"
:touched="meta.touched"
>
<Fieldset.Root>
<template #element="{ props, elementRef }">
<Slider.Root
v-bind="props"
:ref="elementRef"
:model-value="value"
thumb-alignment="edge"
:min="0"
:max="1"
:step="0.01"
:format="{ style: 'percent', minimumFractionDigits: 0, maximumFractionDigits: 0 }"
class="w-full gap-y-2"
@update:model-value="handleChange"
@value-committed="(committed) => handleChange(committed)"
>
<Fieldset.Legend>Scaling threshold</Fieldset.Legend>
<Slider.Value class="col-start-2 text-end" />
<Slider.Control>
<Slider.Track>
<Slider.Indicator />
<Slider.Thumb :index="0" aria-label="Minimum threshold" @focusout="handleBlur" />
<Slider.Thumb :index="1" aria-label="Maximum threshold" @focusout="handleBlur" />
</Slider.Track>
</Slider.Control>
</Slider.Root>
</template>
</Fieldset.Root>
</Field.Root>
</VeeField>
<VeeField
v-slot="{ field, value, meta, errorMessage, handleChange, handleBlur }"
name="storageType"
>
<Field.Root
:name="field.name"
:invalid="!!errorMessage"
:dirty="meta.dirty"
:touched="meta.touched"
>
<Fieldset.Root>
<template #element="{ props, elementRef }">
<RadioGroup
v-bind="props"
:ref="elementRef"
:model-value="value"
class="gap-4"
@update:model-value="handleChange"
>
<Fieldset.Legend class="-mt-px">Storage type</Fieldset.Legend>
<Field.Item>
<Field.Label>
<Radio value="ssd" @blur="handleBlur" />
SSD
</Field.Label>
</Field.Item>
<Field.Item>
<Field.Label>
<Radio value="hdd" @blur="handleBlur" />
HDD
</Field.Label>
</Field.Item>
</RadioGroup>
</template>
</Fieldset.Root>
</Field.Root>
</VeeField>
<VeeField
v-slot="{ field, value, meta, errorMessage, handleChange, handleBlur }"
name="restartOnFailure"
>
<Field.Root
:name="field.name"
:invalid="!!errorMessage"
:dirty="meta.dirty"
:touched="meta.touched"
>
<Field.Label class="gap-2">
Restart on failure
<span class="relative flex shrink-0"
><Switch
:model-value="value"
@update:model-value="handleChange"
@blur="handleBlur" /><span
class="pointer-events-none absolute top-[0.1875rem] left-[0.1875rem] size-3.5 bg-neutral-950 transition-[translate,background-color] duration-150 ease-[ease] peer-checked:translate-x-4 peer-checked:bg-white dark:bg-white dark:peer-checked:bg-neutral-950"
/></span>
</Field.Label>
</Field.Root>
</VeeField>
<VeeField
v-slot="{ field, value, meta, errorMessage, handleChange, handleBlur }"
name="allowedNetworkProtocols"
>
<Field.Root
:name="field.name"
:invalid="!!errorMessage"
:dirty="meta.dirty"
:touched="meta.touched"
>
<Fieldset.Root>
<template #element="{ props, elementRef }">
<CheckboxGroup
v-bind="props"
:ref="elementRef"
:model-value="value"
@update:model-value="handleChange"
>
<Fieldset.Legend class="mb-2">Allowed network protocols</Fieldset.Legend>
<div class="flex gap-4">
<Field.Item v-for="protocol in protocols" :key="protocol">
<Field.Label class="uppercase">
<span class="relative flex shrink-0"
><Checkbox :value="protocol" @blur="handleBlur" /><CheckIcon
class="pointer-events-none absolute inset-0 hidden text-white peer-checked:block dark:text-neutral-950"
/></span>
{{ protocol }}
</Field.Label>
</Field.Item>
</div>
</CheckboxGroup>
</template>
</Fieldset.Root>
</Field.Root>
</VeeField>
<Button type="submit" class="mt-3">Launch server</Button>
</form>
</template>Initialize the form
Initialize the form with the useForm function. Give the initial value of each field, by its name, in initialValues:
<script setup lang="ts">
import { useForm } from 'vee-validate';
interface FormValues {
username: string;
email: string;
}
useForm<FormValues>({
initialValues: {
username: '',
email: '',
},
});
</script>Integrate components
Put the <Field> component of VeeValidate around <Field.Root>. Its default slot gives the state of the field. Give the slot props to these parts:
componentField.namegoes to thenameprop of<Field.Root>.errorMessageis the text of<Field.Error>.!!errorMessagegoes toinvalidof<Field.Root>, and the error then shows.meta.touchedandmeta.dirtygo totouchedanddirtyof<Field.Root>.- Bind
componentField.modelValueto<Input>. UsecomponentField['onUpdate:modelValue']for its model update andcomponentField.onBlurfor blur. VeeValidate then receives each accepted edit once.
<script setup lang="ts">
import { Field as VeeField, useForm } from 'vee-validate';
import { Field } from '@vase-ui/vue/field';
import { Input } from '@vase-ui/vue/input';
useForm({ initialValues: { username: '' } });
</script>
<template>
<VeeField v-slot="{ componentField, meta, errorMessage }" name="username">
<Field.Root
:name="componentField.name"
:invalid="!!errorMessage"
:touched="meta.touched"
:dirty="meta.dirty"
>
<Field.Label>Username</Field.Label>
<Field.Description>
May appear where you contribute or are mentioned. You can remove it at any time.
</Field.Description>
<Input
placeholder="e.g. alice132"
:model-value="componentField.modelValue"
@update:model-value="componentField['onUpdate:modelValue']"
@blur="componentField.onBlur"
/>
<Field.Error>{{ errorMessage }}</Field.Error>
</Field.Root>
</VeeField>
</template>For a composite control, pass value to modelValue and handleChange to update:modelValue. Attach handleBlur to the part that takes focus.
Field validation
Give <Field> a rules function. It returns true when the value is valid, or an error message. Give !!errorMessage to invalid of <Field.Root> to show the message:
<script setup lang="ts">
import { Field as VeeField, useForm } from 'vee-validate';
import { Field } from '@vase-ui/vue/field';
import { Input } from '@vase-ui/vue/input';
useForm({ initialValues: { username: '' } });
function validateUsername(value: unknown) {
if (typeof value !== 'string' || value === '') {
return 'This is a required field.';
}
if (value.length < 2) {
return 'Too short';
}
return true;
}
</script>
<template>
<VeeField
v-slot="{ componentField, meta, errorMessage }"
name="username"
:rules="validateUsername"
>
<Field.Root
:name="componentField.name"
:invalid="!!errorMessage"
:touched="meta.touched"
:dirty="meta.dirty"
>
<Field.Label>Username</Field.Label>
<Input
:model-value="componentField.modelValue"
@update:model-value="componentField['onUpdate:modelValue']"
@blur="componentField.onBlur"
/>
<Field.Error>{{ errorMessage }}</Field.Error>
</Field.Root>
</VeeField>
</template>VeeValidate gives the function a value of the type unknown. Check the type in the function.
Submitting data
Wrap your submit function with handleSubmit. It validates the form. When the form is valid, it calls your function with the values as an object. Bind the result to the submit event of a native <form>.
handleSubmit takes a second function. VeeValidate calls it when the form is not valid, with the errors by field name. The names are in the sequence in which the fields mount. Find the element of the form that has the first name. Move the focus to that element:
<script setup lang="ts">
import { useForm } from 'vee-validate';
import { useTemplateRef } from 'vue';
interface FormValues {
username: string;
email: string;
}
const { handleSubmit } = useForm<FormValues>();
async function submitForm(data: FormValues) {
// Change the object, or send it to a server.
await fetch('https://api.example.com/users', { method: 'POST', body: JSON.stringify(data) });
}
const formElement = useTemplateRef('formElement');
const onSubmit = handleSubmit(submitForm, ({ errors }) => {
const [name] = Object.keys(errors);
const named = formElement.value?.querySelector<HTMLInputElement>(`[name="${name}"]`);
const target =
named?.type === 'hidden'
? named.parentElement?.querySelector<HTMLElement>(
'input:not([type="hidden"]), [role="combobox"]',
)
: named;
target?.focus();
});
</script>
<template>
<form ref="formElement" novalidate @submit="onSubmit">
<!-- form fields -->
<button type="submit">Submit</button>
</form>
</template>Where a part has a hidden input, as Select, Combobox and NumberField have, that input has the name. The input of NumberField gives the focus to its control. The named inputs of Select and Combobox are type="hidden", so the code gives the focus to the text input or the trigger in the same root.
Do not use Form here. A field that shows an error stops the submit event of Form. handleSubmit then does not run, and VeeValidate does not show the errors of the other fields. Add novalidate, as Form does, so that the browser shows no message of its own.
TanStack Form
TanStack Form is a form library with a function-based API for validation. It also works with Vase UI.
<script setup lang="ts">
import { ToastProvider } from '../../components/toast';
import TanstackForm from './TanstackForm.vue';
</script>
<template>
<ToastProvider aria-label="TanStack Form notifications">
<TanstackForm />
</ToastProvider>
</template><script setup lang="ts">
import { revalidateLogic, useForm } from '@tanstack/vue-form';
import type { DeepKeys, ValidationError } from '@tanstack/vue-form';
import { h, useTemplateRef } from 'vue';
import type { FunctionalComponent } from 'vue';
import * as Autocomplete from '../../components/autocomplete';
import { Button } from '../../components/button';
import { Checkbox } from '../../components/checkbox';
import { CheckboxGroup } from '../../components/checkbox-group';
import * as Combobox from '../../components/combobox';
import * as Field from '../../components/field';
import * as Fieldset from '../../components/fieldset';
import { Input } from '../../components/input';
import * as NumberField from '../../components/number-field';
import { Radio } from '../../components/radio';
import { RadioGroup } from '../../components/radio-group';
import * as Select from '../../components/select';
import * as Slider from '../../components/slider';
import { Switch } from '../../components/switch';
import { useToastManager } from '../../components/toast';
interface FormValues {
serverName: string;
region: string | null;
containerImage: string;
serverType: string | null;
numOfInstances: number | null;
scalingThreshold: number[];
storageType: 'ssd' | 'hdd';
restartOnFailure: boolean;
allowedNetworkProtocols: string[];
}
const defaultValues: FormValues = {
serverName: '',
region: null,
containerImage: '',
serverType: null,
numOfInstances: null,
scalingThreshold: [0.2, 0.8],
storageType: 'ssd',
restartOnFailure: true,
allowedNetworkProtocols: [],
};
const requiredFields: (keyof FormValues)[] = [
'serverName',
'region',
'containerImage',
'serverType',
'numOfInstances',
];
const toastManager = useToastManager();
const formElement = useTemplateRef('formElement');
const form = useForm({
defaultValues,
onSubmit: ({ value: formValues }) => {
toastManager.add({
title: 'Form submitted',
description: 'The form contains these values:',
data: formValues,
});
},
onSubmitInvalid: () => {
formElement.value?.querySelector<HTMLElement>('[aria-invalid="true"]')?.focus();
},
validationLogic: revalidateLogic({
mode: 'submit',
modeAfterSubmission: 'change',
}),
validators: {
onDynamic: ({ value: formValues }) => {
const errors: Partial<Record<DeepKeys<FormValues>, ValidationError>> = {};
for (const requiredField of requiredFields) {
if (!formValues[requiredField]) {
errors[requiredField] = 'This is a required field.';
}
}
if (formValues.serverName && formValues.serverName.length < 3) {
errors.serverName = 'At least 3 characters.';
}
return Object.keys(errors).length === 0 ? undefined : { form: errors, fields: errors };
},
},
});
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
const CaretUpDownIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'currentColor', ...attrs }, [
h('path', { d: 'M11 10H5l3 3.5zm0-4H5l3-3.5z' }),
]);
const CheckIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'none', stroke: 'currentColor', ...attrs }, [
h('path', { d: 'm2.5 8.5 4 4 7-9' }),
]);
const PlusIcon: FunctionalComponent = (_, { attrs }) =>
h(
'svg',
{
...ICON_PROPS,
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
...attrs,
},
[h('path', { d: 'M1.5 8h13M8 14.5v-13' })],
);
const MinusIcon: FunctionalComponent = (_, { attrs }) =>
h(
'svg',
{
...ICON_PROPS,
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
...attrs,
},
[h('path', { d: 'M1.5 8h13' })],
);
function cartesian(...arrays: string[][]): string[][] {
return arrays.reduce<string[][]>(
(acc, curr) => acc.flatMap((a) => curr.map((b) => [...a, b])),
[[]],
);
}
const REGIONS = cartesian(['us', 'eu', 'ap'], ['central', 'east', 'west'], ['1', '2', '3']).map(
(part) => part.join('-'),
);
interface Image {
url: string;
name: string;
}
const IMAGES: Image[] = [
'nginx:1.29-alpine',
'node:22-slim',
'postgres:18',
'redis:8.2.2-alpine',
].map((name) => ({ url: `docker.io/library/${name}`, name }));
const storageTypes = ['ssd', 'hdd'];
const protocols = ['http', 'https', 'ssh'];
const SERVER_TYPES = [
{ label: 'Select server type', value: null },
...cartesian(['t', 'm'], ['1', '2'], ['small', 'medium', 'large']).map((part) => {
const value = part.join('.').replace('.', '');
return { label: value, value };
}),
];
// The input of a slider thumb has the focus, and `blur` does not bubble. The thumbs thus listen
// to `focusout`.
const popupHiddenClass = 'scale-[0.98] opacity-0';
</script>
<template>
<form
ref="formElement"
aria-label="Launch new cloud server with TanStack Form"
novalidate
class="flex w-full max-w-3xs flex-col gap-5 sm:max-w-[20rem]"
@submit.prevent="form.handleSubmit()"
>
<form.Field v-slot="{ field }" name="serverName">
<Field.Root
:name="field.name"
:invalid="!field.state.meta.isValid"
:dirty="field.state.meta.isDirty"
:touched="field.state.meta.isTouched"
>
<Field.Label>Server name</Field.Label>
<Input
:model-value="field.state.value"
placeholder="e.g. api-server-01"
@value-change="field.handleChange"
@blur="field.handleBlur"
/>
<Field.Description>Must be 3 or more characters long</Field.Description>
<Field.Error>
{{ field.state.meta.errors.join(',') }}
</Field.Error>
</Field.Root>
</form.Field>
<form.Field v-slot="{ field }" name="region">
<Field.Root
:name="field.name"
:invalid="!field.state.meta.isValid"
:dirty="field.state.meta.isDirty"
:touched="field.state.meta.isTouched"
>
<Combobox.Root
:items="REGIONS"
:model-value="field.state.value"
@value-change="field.handleChange"
>
<div class="relative text-sm leading-5 font-bold text-neutral-950 dark:text-white">
<Field.Label class="mb-1 block">Region</Field.Label>
<Combobox.InputGroup>
<Combobox.Input placeholder="e.g. eu-central-1" @blur="field.handleBlur" />
<div
class="absolute right-0 bottom-0 inline-flex h-full items-center justify-center text-neutral-500 dark:text-neutral-400"
>
<Combobox.Clear />
<Combobox.Trigger>
<Combobox.CaretDownIcon />
</Combobox.Trigger>
</div>
</Combobox.InputGroup>
</div>
<Combobox.Portal>
<Combobox.Positioner>
<Combobox.Popup>
<Combobox.Empty>No matches</Combobox.Empty>
<Combobox.List>
<template #item="{ item }">
<Combobox.Item v-slot="{ state }" :value="item">
<span v-if="state.selected" class="col-start-1">
<CheckIcon />
</span>
<span class="col-start-2">{{ item }}</span>
</Combobox.Item>
</template>
</Combobox.List>
</Combobox.Popup>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
<Field.Error>
{{ field.state.meta.errors.join(',') }}
</Field.Error>
</Field.Root>
</form.Field>
<form.Field v-slot="{ field }" name="containerImage">
<Field.Root
:name="field.name"
:invalid="!field.state.meta.isValid"
:dirty="field.state.meta.isDirty"
:touched="field.state.meta.isTouched"
>
<Autocomplete.Root
:items="IMAGES"
mode="both"
:model-value="field.state.value"
:item-to-string-value="(itemValue: Image) => itemValue.url"
@value-change="field.handleChange"
>
<Field.Label>Container image</Field.Label>
<Autocomplete.Input
placeholder="e.g. docker.io/library/node:latest"
@blur="field.handleBlur"
/>
<Field.Description>Enter a registry URL with optional tags</Field.Description>
<Autocomplete.Portal>
<Autocomplete.Positioner>
<Autocomplete.Popup>
<Autocomplete.List>
<template #item="{ item }">
<Autocomplete.Item :value="item">
<span>{{ item.name }}</span>
<span class="font-mono whitespace-nowrap text-xs opacity-80">{{
item.url
}}</span>
</Autocomplete.Item>
</template>
</Autocomplete.List>
</Autocomplete.Popup>
</Autocomplete.Positioner>
</Autocomplete.Portal>
</Autocomplete.Root>
<Field.Error>
{{ field.state.meta.errors.join(',') }}
</Field.Error>
</Field.Root>
</form.Field>
<form.Field v-slot="{ field }" name="serverType">
<Field.Root
:name="field.name"
:invalid="!field.state.meta.isValid"
:dirty="field.state.meta.isDirty"
:touched="field.state.meta.isTouched"
>
<Select.Root
:items="SERVER_TYPES"
:model-value="field.state.value"
@value-change="field.handleChange"
>
<div class="w-fit space-y-1">
<Select.Label>Server type</Select.Label>
<Select.Trigger class="w-48" @blur="field.handleBlur">
<Select.Value />
<Select.Icon>
<CaretUpDownIcon />
</Select.Icon>
</Select.Trigger>
</div>
<Select.Portal>
<Select.Positioner>
<Transition :enter-from-class="popupHiddenClass" :leave-to-class="popupHiddenClass">
<Select.Popup>
<Select.ScrollUpArrow />
<Select.List>
<Select.Item
v-for="{ label, value } in SERVER_TYPES"
:key="label"
:value="value"
v-slot="{ state }"
>
<span v-if="state.selected" class="col-start-1">
<CheckIcon />
</span>
<Select.ItemText>{{ label }}</Select.ItemText>
</Select.Item>
</Select.List>
<Select.ScrollDownArrow />
</Select.Popup>
</Transition>
</Select.Positioner>
</Select.Portal>
</Select.Root>
<Field.Error>
{{ field.state.meta.errors.join(',') }}
</Field.Error>
</Field.Root>
</form.Field>
<form.Field v-slot="{ field }" name="numOfInstances">
<Field.Root
:name="field.name"
:invalid="!field.state.meta.isValid"
:dirty="field.state.meta.isDirty"
:touched="field.state.meta.isTouched"
>
<NumberField.Root
:model-value="field.state.value"
:min="1"
:max="64"
@value-change="field.handleChange"
>
<Field.Label>Number of instances</Field.Label>
<NumberField.Group>
<NumberField.Decrement aria-label="Decrease">
<MinusIcon />
</NumberField.Decrement>
<NumberField.Input @blur="field.handleBlur" />
<NumberField.Increment aria-label="Increase">
<PlusIcon />
</NumberField.Increment>
</NumberField.Group>
</NumberField.Root>
<Field.Error>
{{ field.state.meta.errors.join(',') }}
</Field.Error>
</Field.Root>
</form.Field>
<form.Field v-slot="{ field }" name="scalingThreshold">
<Field.Root
:name="field.name"
:invalid="!field.state.meta.isValid"
:dirty="field.state.meta.isDirty"
:touched="field.state.meta.isTouched"
>
<Fieldset.Root>
<template #element="{ props, elementRef }">
<Slider.Root
v-bind="props"
:ref="elementRef"
:model-value="field.state.value"
thumb-alignment="edge"
:min="0"
:max="1"
:step="0.01"
:format="{ style: 'percent', minimumFractionDigits: 0, maximumFractionDigits: 0 }"
class="w-full gap-y-2"
@value-change="field.handleChange"
@value-committed="field.handleChange"
>
<Fieldset.Legend>Scaling threshold</Fieldset.Legend>
<Slider.Value class="col-start-2 text-end" />
<Slider.Control>
<Slider.Track>
<Slider.Indicator />
<Slider.Thumb
:index="0"
aria-label="Minimum threshold"
@focusout="field.handleBlur"
/>
<Slider.Thumb
:index="1"
aria-label="Maximum threshold"
@focusout="field.handleBlur"
/>
</Slider.Track>
</Slider.Control>
</Slider.Root>
</template>
</Fieldset.Root>
<Field.Error>
{{ field.state.meta.errors.join(',') }}
</Field.Error>
</Field.Root>
</form.Field>
<form.Field v-slot="{ field }" name="storageType">
<Field.Root
:name="field.name"
:invalid="!field.state.meta.isValid"
:dirty="field.state.meta.isDirty"
:touched="field.state.meta.isTouched"
>
<Fieldset.Root>
<template #element="{ props, elementRef }">
<RadioGroup
v-bind="props"
:ref="elementRef"
:model-value="field.state.value"
class="gap-4"
@value-change="field.handleChange"
>
<Fieldset.Legend class="-mt-px">Storage type</Fieldset.Legend>
<Field.Item v-for="storageType in storageTypes" :key="storageType">
<Field.Label class="uppercase">
<Radio :value="storageType" />
{{ storageType }}
</Field.Label>
</Field.Item>
</RadioGroup>
</template>
</Fieldset.Root>
<Field.Error>
{{ field.state.meta.errors.join(',') }}
</Field.Error>
</Field.Root>
</form.Field>
<form.Field v-slot="{ field }" name="restartOnFailure">
<Field.Root
:name="field.name"
:invalid="!field.state.meta.isValid"
:dirty="field.state.meta.isDirty"
:touched="field.state.meta.isTouched"
>
<Field.Label class="gap-2">
Restart on failure
<span class="relative flex shrink-0"
><Switch
:model-value="field.state.value"
@checked-change="field.handleChange"
@blur="field.handleBlur" /><span
class="pointer-events-none absolute top-[0.1875rem] left-[0.1875rem] size-3.5 bg-neutral-950 transition-[translate,background-color] duration-150 ease-[ease] peer-checked:translate-x-4 peer-checked:bg-white dark:bg-white dark:peer-checked:bg-neutral-950"
/></span>
</Field.Label>
<Field.Error>
{{ field.state.meta.errors.join(',') }}
</Field.Error>
</Field.Root>
</form.Field>
<form.Field v-slot="{ field }" name="allowedNetworkProtocols">
<Field.Root
:name="field.name"
:invalid="!field.state.meta.isValid"
:dirty="field.state.meta.isDirty"
:touched="field.state.meta.isTouched"
>
<Fieldset.Root>
<template #element="{ props, elementRef }">
<CheckboxGroup
v-bind="props"
:ref="elementRef"
:model-value="field.state.value"
@value-change="field.handleChange"
>
<Fieldset.Legend class="mb-2">Allowed network protocols</Fieldset.Legend>
<div class="flex gap-4">
<Field.Item v-for="protocol in protocols" :key="protocol">
<Field.Label class="uppercase">
<span class="relative flex shrink-0"
><Checkbox :value="protocol" @blur="field.handleBlur" /><CheckIcon
class="pointer-events-none absolute inset-0 hidden text-white peer-checked:block dark:text-neutral-950"
/></span>
{{ protocol }}
</Field.Label>
</Field.Item>
</div>
</CheckboxGroup>
</template>
</Fieldset.Root>
<Field.Error>
{{ field.state.meta.errors.join(',') }}
</Field.Error>
</Field.Root>
</form.Field>
<Button type="submit" class="mt-3">Launch server</Button>
</form>
</template>Initialize the form
Create a form instance with the useForm function. Give the initial value of each field, by its name, in defaultValues:
interface FormValues {
username: string;
email: string;
}
const defaultValues: FormValues = {
username: '',
email: '',
};
const form = useForm({
defaultValues,
});Integrate components
Use the <form.Field> component of the form instance. Its default slot gives field. Give its members to these parts:
field.namegoes to thenameprop of<Field.Root>.field.state.meta.isValid,isDirtyandisTouchedgo toinvalid,dirtyandtouchedof<Field.Root>.invalidtakes the opposite ofisValid.field.state.value,field.handleChangeandfield.handleBlurgo to themodelValueprop, thevalueChangeevent and theblurevent of the control.
<script setup lang="ts">
import { useForm } from '@tanstack/vue-form';
import { Field } from '@vase-ui/vue/field';
import { Input } from '@vase-ui/vue/input';
const form = useForm({ defaultValues: { username: '' } });
</script>
<template>
<form>
<form.Field v-slot="{ field }" name="username">
<Field.Root
:name="field.name"
:invalid="!field.state.meta.isValid"
:dirty="field.state.meta.isDirty"
:touched="field.state.meta.isTouched"
>
<Field.Label>Username</Field.Label>
<Input
:model-value="field.state.value"
placeholder="e.g. bob276"
@value-change="field.handleChange"
@blur="field.handleBlur"
/>
<Field.Error>
{{ field.state.meta.errors.join(',') }}
</Field.Error>
</Field.Root>
</form.Field>
</form>
</template>The Form component of Vase UI is not needed with TanStack Form.
Form validation
To validate like a native <form>:
- Call
revalidateLogic, and give the result tovalidationLogicinuseForm. - Give a function to
validators.onDynamicinuseForm. It returns an object with the keysformandfields. Each key holds the errors by field name.
The form then validates all fields at the first submit. After that, it validates again each time that a value changes.
<script setup lang="ts">
import { revalidateLogic, useForm } from '@tanstack/vue-form';
const form = useForm({
defaultValues: {
username: '',
email: '',
},
validationLogic: revalidateLogic({
mode: 'submit',
modeAfterSubmission: 'change',
}),
validators: {
onDynamic: ({ value: formValues }) => {
const errors: { username?: string; email?: string } = {};
if (!formValues.username) {
errors.username = 'Username is required.';
} else if (formValues.username.length < 3) {
errors.username = 'At least 3 characters.';
}
if (!formValues.email) {
errors.email = 'Email is required.';
} else if (!formValues.email.includes('@')) {
errors.email = 'Invalid email address.';
}
return { form: errors, fields: errors };
},
},
});
</script>
<template>
<form @submit.prevent="form.handleSubmit()" />
</template>Field validation
Give validators to a <form.Field> to validate that field with a function of its own:
<script setup lang="ts">
import { useForm } from '@tanstack/vue-form';
import { Field } from '@vase-ui/vue/field';
const form = useForm({ defaultValues: { username: '' } });
async function checkUsername({ value: username }: { value: string }) {
const result = await fetch(`https://api.example.com/usernames/${encodeURIComponent(username)}`);
return result.ok ? undefined : `${username} is not available.`;
}
</script>
<template>
<form>
<form.Field v-slot="{ field }" name="username" :validators="{ onChangeAsync: checkUsername }">
<Field.Root :name="field.name" />
</form.Field>
</form>
</template>Submitting data
To submit the form:
- Give a submit function to
onSubmitinuseForm. - Call
form.handleSubmit()from an event listener, such as@submit.preventon the form or@clickon a button. - Give a function to
onSubmitInvalidinuseForm. TanStack Form calls it when the form is not valid. Vase UI givesaria-invalid="true"to the control of a field that is invalid. Find the first such element in the form. Move the focus to that element.
<script setup lang="ts">
import { useForm } from '@tanstack/vue-form';
import { useTemplateRef } from 'vue';
const formElement = useTemplateRef('formElement');
const form = useForm({
defaultValues: { username: '' },
onSubmit: async ({ value: formValues }) => {
await fetch('https://api.example.com/users', {
method: 'POST',
body: JSON.stringify(formValues),
});
},
onSubmitInvalid: () => {
formElement.value?.querySelector<HTMLElement>('[aria-invalid="true"]')?.focus();
},
});
</script>
<template>
<form ref="formElement" @submit.prevent="form.handleSubmit()">
<!-- form fields -->
<button type="submit">Submit</button>
</form>
</template>Differences from Base UI
| Base UI | Vase UI |
|---|---|
onFormSubmit(formValues, eventDetails) | The submit event of Form, with the native SubmitEvent and the values. It comes after the validation passes. |
onSubmit with event.preventDefault() | @submit on Form. The form prevents the native submit while it has a submit listener. |
errors of Form | v-model:errors. An edit of a field removes the key of that field. |
validationMode: onSubmit, onBlur, onChange | validationMode: submit, blur, change. |
actionsRef of Form and Field.Root | A template ref with validate(). The validate(name?) of Form returns true when each field that it checks is valid. |
dirty and touched of Field.Root | v-model:dirty and v-model:touched. |
Field.Control | Input. |
Field.Validity | The default slot of Field.Root. It gives state, validity, errors, value and initialValue. |
match={true} on Field.Error | invalid on Field.Root. Field.Error with no match shows while the field is invalid. |
| React Hook Form | VeeValidate, a form library for Vue. |