Introducing KickStart —  AI generated FormKit forms in seconds. Generate from a screenshot, edit with drag-and-drop or conversational AI, copy & paste as components or schema!
Try for free

Início rápido da instalação Pro 🚀

Unit Input

The unit input allows for restricted input of values based on the provided unit (distance, weight, temperature, etc.) and locale.

Carregar exemplo ao vivo

Props

Unit

The unit prop is the type of unit you want to display. A full list of allowed unit types are listed below:

  • acre
  • bit
  • byte
  • celsius
  • centimeter
  • day
  • degree
  • fahrenheit
  • fluid-ounce
  • foot
  • gallon
  • gigabit
  • gigabyte
  • gram
  • hectare
  • hour
  • inch
  • kilobit
  • kilobyte
  • kilogram
  • kilometer
  • liter
  • megabit
  • megabyte
  • meter
  • microsecond
  • mile
  • mile-scandinavian
  • milliliter
  • millimeter
  • millisecond
  • minute
  • month
  • nanosecond
  • ounce
  • percent
  • petabyte
  • pound
  • second
  • stone
  • terabit
  • terabyte
  • week
  • yard
  • year

Unit display

The display length can be modified by the unitDisplay property. Accepted values are short, narrow, and long.

Carregar exemplo ao vivo

Locale

By default the locale will use what you have set in your formkit.config.ts as the desired locale. However you can override this with the displayLocale prop. For example, en-US, de-DE, en-IN, zh-CN, etc, etc.

Carregar exemplo ao vivo

Decimals

By default the decimals will display when the value contains the unit/locale decimal separator and will show default formatting decimal places to display for the given unit, however you can override this. By setting decimals to false or 0, the value will not allow decimals or setting decimals to a numeric value will limit the maximum decimal places to that value.

You can also choose to set a minimum number of decimals with the minDecimals prop. For example, you always want to show 2 decimal places you would set minDecimals="2".

Carregar exemplo ao vivo

Minimum and Maximum Values

Similar to a number input, you can set a min and max value.

Carregar exemplo ao vivo

Step

Again, similar to a number input you can use the up/down keys to step the value. By default the step is 1 but you can override that with this prop.

Carregar exemplo ao vivo

Value Formatting

The value of the input itself defaults to a number but can be formatted as a string to include information about the unit itself.

Carregar exemplo ao vivo

Value unit

The unit input also allows for first-party conversion of one unit type to another. In this example, we will use unit of type mile, but the value itself will be converted to kilometers when setting value-unit to kilometer.

Carregar exemplo ao vivo

Unitless

The unit prop is optional, allowing for unitless values.

Carregar exemplo ao vivo
Mixed unit types

In order to convert one unit to another, they must be in the same taxonomy (so for example, you can not convert kilometers to liters).

Props & Attributes

PropTypePadrãoDescrição
unitstring | undefinedSet the specified unit to use for this input. If undefined, will allow for unitless values.
displayLocalestringen-USSet the desired display locale to use for this input
decimalsboolean|numbernullChoose to either completely disallow decimals or override the maximum number of decimals for the input
minDecimalsnumbernullChoose to show a minimum number of decimals should your input require this
minnumbernullMinimum numeric value allowed. If zero or above, negatives will not be allowed
maxnumbernullMaximum numeric value allowed for this input
stepnumber1When using the up/down keys, how much to modify the current value.
valueDecimalsstring | numberundefinedDetermines the allowed number of decimals for the valueUnit.
valueFormatstringnumberChoose between number and string whether you want a numeric value or a parsed string value
valueUnitstringundefinedUsed to convert the user-inputted value from one unit to another
unitDisplaystring ('narrow' | 'short' | 'long')shortDetermines the length of the how the unit is represented.
Mostrar Universal props
configObject{}Opções de configuração a serem fornecidas para o nó do input e qualquer nó descendente deste input.
delayNumber20Número de milissegundos para debounce do valor do input antes de despachar o commit hook.
dirtyBehaviorstringtouchedDetermina como o indicador "dirty" deste input é definido. Pode ser configurado como touched ou compare - touched (o padrão) é mais performático, mas não detectará quando o formulário corresponder novamente ao seu estado inicial.
errorsArray[]Array de strings para exibir como mensagens de erro neste campo.
helpString''Texto para o texto de ajuda associado ao input.
idStringinput_{n}O ID único do input. Fornecer um ID também permite acesso global ao nó do input.
ignoreBooleanfalseImpede que um input seja incluído em qualquer pai (grupo, lista, formulário etc). Útil ao usar inputs para a interface do usuário em vez de valores reais.
indexNumberundefinedPermite que um input seja inserido no índice fornecido, se o pai for uma lista. Se o valor do input for indefinido, ele herda o valor dessa posição de índice. Se ele tiver um valor, ele o insere nos valores da lista no índice fornecido.
labelString''Texto para o elemento label associado ao input.
nameStringinput_{n}O nome do input como identificado no objeto de dados. Isso deve ser único dentro de um grupo de campos.
parentFormKitNodecontextualPor padrão, o pai é um grupo, lista ou formulário de envolvimento, mas essa prop permite a atribuição explícita do nó pai.
prefix-iconString''Especifica um ícone para colocar na seção prefixIcon.
preservebooleanfalsePreserva o valor do input em um grupo pai, lista ou formulário quando o input é desmontado.
preserve-errorsbooleanfalsePor padrão, os erros definidos em inputs usando setErrors são automaticamente limpos no input. Definir essa prop como true mantém o erro até que ele seja explicitamente limpo.
sections-schemaObject{}Um objeto de chaves de seção e valores parciais de esquema, em que cada esquema parcial é aplicado à seção respectiva.
suffix-iconString''Especifica um ícone para colocar na seção suffixIcon.
typeStringtextO tipo de input a ser renderizado pela biblioteca.
validationString, Array[]As regras de validação a serem aplicadas ao input.
validation-visibilityStringblurDetermina quando mostrar as regras de validação com falha de um input. Os valores válidos são blur, dirty e live.
validation-labelString{label prop}Determina qual rótulo usar nas mensagens de erro de validação, por padrão, usa a propriedade label, se disponível, caso contrário, usa a propriedade name.
validation-rulesObject{}Regras de validação personalizadas adicionais para disponibilizar na propriedade de validação.
valueAnyundefinedInicializa o valor do input e/ou de seus filhos. Não é reativo. Pode inicializar grupos inteiros (formulários) e listas..

Sections

Você pode direcionar uma seção específica de uma entrada usando a "key" dessa seção, permitindo que você modifique as classes, HTML (por meio de :sections-schema ou o conteúdo (por meio de slots) dessa seção). Saiba mais sobre as seções aqui.

Unit input diagram

Unit Input
100 mi
Help text goes here
Any messages would appear here