본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

quasar-vue-components-input

원문 보기 위키 갱신

QInput 컴포넌트는 사용자로부터 텍스트 입력을 받는 데 사용하는 컴포넌트예요. 일반 input처럼 v-model을 사용하며, 오류 표시와 검증(validation)을 지원하고 다양한 스타일·색상·타입을 선택할 수 있어요.

출처: 문서

본문

QInput API

Props

  • name (string, optional) Used to specify the name of the control; Useful if dealing with forms; If not specified, it takes the value of 'for' prop, if it exists Examples: 'car_id'
  • mask (string, optional) Custom mask or one of the predefined mask names Examples:
    • '###-##'
    • 'date'
    • 'datetime'
    • 'time'
    • 'fulltime'
    • 'phone'
    • 'card'
  • fill-mask (boolean | string, optional) Fills string with specified characters (or underscore if value is not string) to fill mask's length Examples: true, '0', '_'
  • reverse-fill-mask (boolean, optional) Fills string from the right side of the mask
  • unmasked-value (boolean, optional) Model will be unmasked (won't contain tokens/separation characters)
  • mask-tokens (object, optional) (added v2.18.4) Object of custom mask tokens to be added on top of the default ones; Can also override any of the default ones Examples:
    • { C: { pattern: '[0-4a-eA-E]', negate: '[^0-4a-eA-E]', transform: v => v.toLocaleUpperCase() } } Object shape:
    • ...tokenCharacter (object, required) The definition for the current custom mask token Examples:
      • { pattern: '[0-4a-eA-E]', negate: '[^0-4a-eA-E]', transform: v => v.toLocaleUpperCase() }
      • { pattern: '[5-8]', negate: '[^5-8]' } Object shape:
      • pattern (string, required) A string representing a regular expression to match against a single character Examples: '[0-9]', '[a-zA-Z]'
      • negate (string, required) A string representing a regular expression to NOT match against a single character Examples: '[^0-9]', '[^a-zA-Z]'
      • transform (Function, optional) A function that takes the character as argument and returns the transformed character Function signature: (char: string) => string Examples: v => v.toLocaleUpperCase() Params:
        • char (string, required) The character being transformed Examples: 'a', '1' Returns: string The transformed character
  • model-value (string | number | FileList, required, syncable) Model of the component; Either use this property (along with a listener for 'update:modelValue' event) OR use v-model directive Examples: v-model="myText"
  • error (boolean, optional), default null Does field have validation errors?; Setting it to a Boolean (even false) reserves the bottom space for the error message so the layout does not shift when the error appears; leave it at null (the default) when not using external validation, or use 'hide-bottom-space' to not reserve the space
  • error-message (string, optional) Validation error message (gets displayed only if 'error' is set to 'true') Examples: 'Username must have at least 5 characters'
  • no-error-icon (boolean, optional) Hide error icon when there is an error
  • rules (any[], optional) Array of Functions/Strings; If String, then it must be a name of one of the embedded validation rules Examples:
    • [val => val.length <= 3 || 'Please use maximum 3 characters']
    • ['fulltime']
    • [(val, rules) => rules.email(val) || 'Please enter a valid email address']
  • reactive-rules (boolean, optional) By default a change in the rules does not trigger a new validation until the model changes; If set to true then a change in the rules will trigger a validation; Has a performance penalty, so use it only when you really need it
  • lazy-rules (boolean | string, optional), default false If set to boolean true then it checks validation status against the 'rules' only when field loses focus; while an error is displayed it re-checks on each model change so the error clears as soon as the value becomes valid; If set to 'ondemand' then it will trigger only when component's validate() method is manually called or when the wrapper QForm submits itself Accepts: true, false, 'ondemand'
  • label (string, optional) A text label that will “float” up above the input field, once the field gets focus Examples: 'Username'
  • stack-label (boolean, optional) Label will be always shown above the field regardless of field content (if any)
  • hint (string, optional) Helper (hint) text which gets placed below your wrapped form component Examples: 'Fill in between 3 and 12 characters'
  • hide-hint (boolean, optional) Hide the helper (hint) text when field doesn't have focus
  • prefix (string, optional) Prefix Examples: '$'
  • suffix (string, optional) Suffix Examples: '@gmail.com'
  • label-color (string, optional) Color name for the label from the Quasar Color Palette; Overrides the 'color' prop; The difference from 'color' prop is that the label will always have this color, even when field is not focused Examples: 'primary', 'teal', 'teal-10'
  • color (string, optional) Color name for component from the Quasar Color Palette Examples: 'primary', 'teal', 'teal-10'
  • bg-color (string, optional) Color name for component from the Quasar Color Palette Examples: 'primary', 'teal', 'teal-10'
  • dark (boolean, optional), default null Notify the component that the background is a dark color
  • loading (boolean, optional) Signals the user a process is in progress by displaying a spinner; Spinner can be customized by using the 'loading' slot.
  • clearable (boolean, optional) Appends clearable icon when a value (not undefined or null) is set; When clicked, model becomes null
  • clear-icon (string, optional) Custom icon to use for the clear button when using along with 'clearable' prop Examples: 'close'
  • filled (boolean, optional) Use 'filled' design for the field
  • outlined (boolean, optional) Use 'outlined' design for the field
  • borderless (boolean, optional) Use 'borderless' design for the field
  • standout (boolean | string, optional) Use 'standout' design for the field; Specifies classes to be applied when focused (overriding default ones); a text color class in there also colors the content and the decorators Examples: true, 'bg-primary text-white'
  • label-slot (boolean, optional) Enables label slot; You need to set it to force use of the 'label' slot if the 'label' prop is not set
  • bottom-slots (boolean, optional) Enables bottom slots ('error', 'hint', 'counter')
  • hide-bottom-space (boolean, optional) Do not reserve space for hint/error/counter anymore when these are not used; As a result, it also disables the animation for those
  • counter (boolean, optional) Show an automatic counter on bottom right
  • rounded (boolean, optional) Applies a small standard border-radius for a squared shape of the component
  • square (boolean, optional) Remove border-radius so borders are squared; Overrides 'rounded' prop
  • dense (boolean, optional) Dense mode; occupies less space
  • item-aligned (boolean, optional) Match inner content alignment to that of QItem
  • disable (boolean, optional) Put component in disabled mode
  • readonly (boolean, optional) Put component in readonly mode
  • autofocus (boolean, optional) Focus field on initial component render
  • for (string, optional) Used to specify the 'id' of the control and also the 'for' attribute of the label that wraps it; If no 'name' prop is specified, then it is used for this attribute as well Examples: 'myFieldsId'
  • shadow-text (string, optional) Text to be displayed as shadow at the end of the text in the control; Does NOT applies to type=file Examples: 'rest of the fill value'
  • type (string, optional), default 'text' Input type Accepts: 'text', 'password', 'textarea', 'email', 'search', 'tel', 'file', 'number', 'url', 'time', 'date', 'datetime-local'
  • debounce (string | number, optional) Debounce amount (in milliseconds) when updating model
  • maxlength (string | number, optional) Specify a max length of model
  • autogrow (boolean, optional) Make field autogrow along with its content (uses a textarea)
  • input-class (string | any[] | object, optional) Class definitions to be attributed to the underlying input tag Examples: 'my-special-class', { 'my-special-class': true }
  • input-style (string | any[] | object, optional) Style definitions to be attributed to the underlying input tag Examples: 'background-color: #ff0000', { backgroundColor: '#ff0000' }

Computed Props

  • hasError (boolean, optional) Whether the component is in error state
  • nativeEl (Element, optional) The native input/textarea DOM Element

Methods

  • resetValidation(): void Reset validation status
  • validate(value?: any): boolean | Promise<boolean> Trigger a validation Params:
    • value (any, optional) Optional value to validate against Returns: boolean | Promise<boolean> True/false if no async rules, otherwise a Promise with the outcome (true -> validation was a success, false -> invalid models detected) Examples: true, validate().then(outcome => { ... })
  • focus(): void Focus underlying input tag
  • blur(): void Lose focus on underlying input tag
  • select(): void Select input text
  • getNativeElement(): Element DEPRECATED; Access 'nativeEl' directly instead; Get the native input/textarea DOM Element Returns: Element The underlying native input/textarea DOM Element

Events

  • @update:model-value Emitted when the component needs to change the model; Is also used by v-model Params:
    • value (string | number, required) New model value
  • @focus Emitted when component gets focused Params:
    • evt (Event, optional) JS event object
  • @blur Emitted when component loses focus Params:
    • evt (Event, optional) JS event object
  • @clear When using the 'clearable' property, this event is emitted when the clear icon is clicked Params:
    • value (any, optional) The previous value before clearing it

Slots

  • #default Field main content
  • #prepend Prepend inner field; Suggestions: QIcon, QBtn
  • #append Append to inner field; Suggestions: QIcon, QBtn
  • #before Prepend outer field; Suggestions: QIcon, QBtn
  • #after Append outer field; Suggestions: QIcon, QBtn
  • #label Slot for label; Used only if 'label-slot' prop is set or the 'label' prop is set; When it is used the text in the 'label' prop is ignored
  • #error Slot for errors; Enabled only if 'bottom-slots' prop is used; Suggestion:
  • #hint Slot for hint text; Enabled only if 'bottom-slots' prop is used; Suggestion:
  • #counter Slot for counter text; Enabled only if 'bottom-slots' prop is used; Suggestion:
  • #loading Override default spinner when component is in loading mode; Use in conjunction with 'loading' prop

디자인 (Design)

[!NOTE] QInput에는 메인 디자인(filled, outlined, standout, borderless) 중 하나만 사용할 수 있어요. 이들은 서로 배타적이라 여러 개를 동시에 쓸 수 없어요.

예시 "Design Overview":

<template>
  <div class="q-gutter-md" style="max-width: 300px">
    <q-input v-model="text" label="Standard" />

    <q-input filled v-model="text" label="Filled" />

    <q-input outlined v-model="text" label="Outlined" />

    <q-input standout v-model="text" label="Standout" />

    <q-input
      standout="bg-teal text-white"
      v-model="text"
      label="Custom standout"
    />

    <q-input borderless v-model="text" label="Borderless" />

    <q-input rounded filled v-model="text" label="Rounded filled" />

    <q-input rounded outlined v-model="text" label="Rounded outlined" />

    <q-input rounded standout v-model="text" label="Rounded standout" />

    <q-input square filled v-model="text" label="Square filled" />

    <q-input square outlined v-model="text" label="Square outlined" />

    <q-input square standout v-model="text" label="Square standout" />
  </div>
</template>

<script setup>
import { ref } from 'vue'

const text = ref('')
</script>

색상 지정 (Coloring)

<template>
  <div class="q-gutter-y-md column" style="max-width: 300px">
    <q-input color="purple-12" v-model="text" label="Label">
      <template #prepend>
        <q-icon name="event" />
      </template>
    </q-input>

    <q-input color="teal" filled v-model="text" label="Label">
      <template #prepend>
        <q-icon name="event" />
      </template>
    </q-input>

    <q-input
      color="grey-3"
      label-color="orange"
      outlined
      v-model="text"
      label="Label"
    >
      <template #append>
        <q-icon name="event" color="orange" />
      </template>
    </q-input>

    <q-input
      color="lime-11"
      bg-color="green"
      filled
      v-model="text"
      label="Label"
    >
      <template #prepend>
        <q-icon name="event" />
      </template>
    </q-input>

    <q-input color="teal" outlined v-model="text" label="Label">
      <template #append>
        <q-avatar>
          <img
            alt="Quasar logo"
            src="https://cdn.quasar.dev/logo-v2/svg/logo.svg"
          />
        </q-avatar>
      </template>
    </q-input>

    <q-input
      color="orange"
      standout
      bottom-slots
      v-model="text"
      label="Label"
      counter
      clearable
    >
      <template #prepend>
        <q-icon name="place" />
      </template>
      <template #append>
        <q-icon name="favorite" />
      </template>

      <template #hint> Field hint </template>
    </q-input>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const text = ref('')
</script>

기본형 (Standard)

<template>
  <div class="q-gutter-y-md column" style="max-width: 300px">
    <q-toggle v-model="dense" label="Dense QInput" />

    <q-input v-model="text" :dense="dense" />

    <q-input
      v-model="text"
      label="Label (stacked)"
      stack-label
      :dense="dense"
    />

    <q-input v-model="text" label="Label" :dense="dense" />

    <q-input
      v-model="ph"
      label="Label"
      placeholder="Placeholder"
      hint="With placeholder"
      :dense="dense"
    />

    <q-input
      v-model="ph"
      placeholder="Placeholder"
      hint="With placeholder"
      :dense="dense"
    />

    <q-input v-model="text" :dense="dense">
      <template #prepend>
        <q-icon name="event" />
      </template>
    </q-input>

    <q-input v-model="text" :dense="dense">
      <template #append>
        <q-avatar>
          <img
            alt="Quasar logo"
            src="https://cdn.quasar.dev/logo-v2/svg/logo.svg"
          />
        </q-avatar>
      </template>
    </q-input>

    <q-input bottom-slots v-model="text" label="Label" counter :dense="dense">
      <template #prepend>
        <q-icon name="place" />
      </template>
      <template #append>
        <q-icon name="close" @click="text = ''" class="cursor-pointer" />
      </template>

      <template #hint> Field hint </template>
    </q-input>

    <q-input
      bottom-slots
      v-model="text"
      label="Label"
      counter
      maxlength="12"
      :dense="dense"
    >
      <template #before>
        <q-icon name="flight_takeoff" />
      </template>

      <template #append>
        <q-icon
          v-if="text !== ''"
          name="close"
          @click="text = ''"
          class="cursor-pointer"
        />
        <q-icon name="search" />
      </template>

      <template #hint> Field hint </template>
    </q-input>

    <q-input
      bottom-slots
      v-model="text"
      label="Label"
      counter
      maxlength="12"
      :dense="dense"
    >
      <template #before>
        <q-avatar>
          <img
            alt="User avatar"
            src="https://cdn.quasar.dev/img/avatar5.jpg"
          />
        </q-avatar>
      </template>

      <template #append>
        <q-icon
          v-if="text !== ''"
          name="close"
          @click="text = ''"
          class="cursor-pointer"
        />
        <q-icon name="schedule" />
      </template>

      <template #hint> Field hint </template>

      <template #after>
        <q-btn round dense flat icon="send" />
      </template>
    </q-input>

    <q-input
      bottom-slots
      v-model="text"
      label="Label"
      counter
      maxlength="12"
      :dense="dense"
    >
      <template #before>
        <q-icon name="event" />
      </template>

      <template #hint> Field hint </template>

      <template #append>
        <q-btn round dense flat icon="add" />
      </template>
    </q-input>

    <q-input v-model="text" hint="Disable" :dense="dense" disable />

    <q-input v-model="text" hint="Readonly" :dense="dense" readonly />

    <q-input
      v-model="text"
      hint="Disable and readonly"
      :dense="dense"
      disable
      readonly
    />
  </div>
</template>

<script setup>
import { ref } from 'vue'

const text = ref('')
const ph = ref('')
const dense = ref(false)
</script>

채움형 (Filled)

<template>
  <div class="q-gutter-y-md column" style="max-width: 300px">
    <q-toggle v-model="dense" label="Dense QInput" />

    <q-input filled v-model="text" :dense="dense" />

    <q-input
      filled
      v-model="text"
      label="Label (stacked)"
      stack-label
      :dense="dense"
    />

    <q-input filled v-model="text" label="Label" :dense="dense" />

    <q-input
      filled
      v-model="ph"
      label="Label"
      placeholder="Placeholder"
      hint="With placeholder"
      :dense="dense"
    />

    <q-input
      filled
      v-model="ph"
      placeholder="Placeholder"
      hint="With placeholder"
      :dense="dense"
    />

    <q-input
      filled
      square
      v-model="text"
      hint="With perfect square borders"
      :dense="dense"
    />

    <q-input filled v-model="text" :dense="dense">
      <template #prepend>
        <q-icon name="event" />
      </template>
    </q-input>

    <q-input filled v-model="text" :dense="dense">
      <template #append>
        <q-avatar>
          <img
            alt="Quasar logo"
            src="https://cdn.quasar.dev/logo-v2/svg/logo.svg"
          />
        </q-avatar>
      </template>
    </q-input>

    <q-input
      filled
      bottom-slots
      v-model="text"
      label="Label"
      counter
      :dense="dense"
    >
      <template #prepend>
        <q-icon name="place" />
      </template>
      <template #append>
        <q-icon name="close" @click="text = ''" class="cursor-pointer" />
      </template>

      <template #hint> Field hint </template>
    </q-input>

    <q-input
      filled
      bottom-slots
      v-model="text"
      label="Label"
      counter
      maxlength="12"
      :dense="dense"
    >
      <template #before>
        <q-icon name="flight_takeoff" />
      </template>

      <template #append>
        <q-icon
          v-if="text !== ''"
          name="close"
          @click="text = ''"
          class="cursor-pointer"
        />
        <q-icon name="search" />
      </template>

      <template #hint> Field hint </template>
    </q-input>

    <q-input
      filled
      bottom-slots
      v-model="text"
      label="Label"
      counter
      maxlength="12"
      :dense="dense"
    >
      <template #before>
        <q-avatar>
          <img
            alt="User avatar"
            src="https://cdn.quasar.dev/img/avatar5.jpg"
          />
        </q-avatar>
      </template>

      <template #append>
        <q-icon
          v-if="text !== ''"
          name="close"
          @click="text = ''"
          class="cursor-pointer"
        />
        <q-icon name="schedule" />
      </template>

      <template #hint> Field hint </template>

      <template #after>
        <q-btn round dense flat icon="send" />
      </template>
    </q-input>

    <q-input
      filled
      bottom-slots
      v-model="text"
      label="Label"
      counter
      maxlength="12"
      :dense="dense"
    >
      <template #before>
        <q-icon name="event" />
      </template>

      <template #hint> Field hint </template>

      <template #append>
        <q-btn round dense flat icon="add" />
      </template>
    </q-input>

    <q-input filled v-model="text" hint="Disable" :dense="dense" disable />

    <q-input filled v-model="text" hint="Readonly" :dense="dense" readonly />

    <q-input
      filled
      v-model="text"
      hint="Disable and readonly"
      :dense="dense"
      disable
      readonly
    />
  </div>
</template>

<script setup>
import { ref } from 'vue'

const text = ref('')
const ph = ref('')
const dense = ref(false)
</script>

아웃라인형 (Outlined)

<template>
  <div class="q-gutter-y-md column" style="max-width: 300px">
    <q-toggle v-model="dense" label="Dense QInput" />

    <q-input outlined v-model="text" :dense="dense" />

    <q-input
      outlined
      v-model="text"
      label="Label (stacked)"
      stack-label
      :dense="dense"
    />

    <q-input outlined v-model="text" label="Label" :dense="dense" />

    <q-input
      outlined
      v-model="ph"
      label="Label"
      placeholder="Placeholder"
      hint="With placeholder"
      :dense="dense"
    />

    <q-input
      outlined
      v-model="ph"
      placeholder="Placeholder"
      hint="With placeholder"
      :dense="dense"
    />

    <q-input
      outlined
      square
      v-model="text"
      hint="With perfect square borders"
      :dense="dense"
    />

    <q-input outlined v-model="text" :dense="dense">
      <template #prepend>
        <q-icon name="event" />
      </template>
    </q-input>

    <q-input outlined v-model="text" :dense="dense">
      <template #append>
        <q-avatar>
          <img
            alt="Quasar logo"
            src="https://cdn.quasar.dev/logo-v2/svg/logo.svg"
          />
        </q-avatar>
      </template>
    </q-input>

    <q-input
      outlined
      bottom-slots
      v-model="text"
      label="Label"
      counter
      :dense="dense"
    >
      <template #prepend>
        <q-icon name="place" />
      </template>
      <template #append>
        <q-icon name="close" @click="text = ''" class="cursor-pointer" />
      </template>

      <template #hint> Field hint </template>
    </q-input>

    <q-input
      outlined
      bottom-slots
      v-model="text"
      label="Label"
      counter
      maxlength="12"
      :dense="dense"
    >
      <template #before>
        <q-icon name="flight_takeoff" />
      </template>

      <template #append>
        <q-icon
          v-if="text !== ''"
          name="close"
          @click="text = ''"
          class="cursor-pointer"
        />
        <q-icon name="search" />
      </template>

      <template #hint> Field hint </template>
    </q-input>

    <q-input
      outlined
      bottom-slots
      v-model="text"
      label="Label"
      counter
      maxlength="12"
      :dense="dense"
    >
      <template #before>
        <q-avatar>
          <img
            alt="User avatar"
            src="https://cdn.quasar.dev/img/avatar5.jpg"
          />
        </q-avatar>
      </template>

      <template #append>
        <q-icon
          v-if="text !== ''"
          name="close"
          @click="text = ''"
          class="cursor-pointer"
        />
        <q-icon name="schedule" />
      </template>

      <template #hint> Field hint </template>

      <template #after>
        <q-btn round dense flat icon="send" />
      </template>
    </q-input>

    <q-input
      outlined
      bottom-slots
      v-model="text"
      label="Label"
      counter
      maxlength="12"
      :dense="dense"
    >
      <template #before>
        <q-icon name="event" />
      </template>

      <template #hint> Field hint </template>

      <template #append>
        <q-btn round dense flat icon="add" />
      </template>
    </q-input>

    <q-input outlined v-model="text" hint="Disable" :dense="dense" disable />

    <q-input
      outlined
      v-model="text"
      hint="Readonly"
      :dense="dense"
      readonly
    />

    <q-input
      outlined
      v-model="text"
      hint="Disable and readonly"
      :dense="dense"
      disable
      readonly
    />
  </div>
</template>

<script setup>
import { ref } from 'vue'

const text = ref('')
const ph = ref('')
const dense = ref(false)
</script>

스탠드아웃 (Standout)

<template>
  <div class="q-gutter-y-md column" style="max-width: 300px">
    <q-toggle v-model="dense" label="Dense QInput" />

    <q-input standout v-model="text" :dense="dense" />

    <q-input
      standout="bg-teal text-white"
      v-model="text"
      label="Custom standout"
      :dense="dense"
    />

    <q-input
      standout
      v-model="text"
      label="Label (stacked)"
      stack-label
      :dense="dense"
    />

    <q-input standout v-model="text" label="Label" :dense="dense" />

    <q-input
      standout
      v-model="ph"
      label="Label"
      placeholder="Placeholder"
      hint="With placeholder"
      :dense="dense"
    />

    <q-input
      standout
      v-model="ph"
      placeholder="Placeholder"
      hint="With placeholder"
      :dense="dense"
    />

    <q-input
      standout
      square
      v-model="text"
      hint="With perfect square borders"
      :dense="dense"
    />

    <q-input standout v-model="text" :dense="dense">
      <template #prepend>
        <q-icon name="event" />
      </template>
    </q-input>

    <q-input standout v-model="text" :dense="dense">
      <template #append>
        <q-avatar>
          <img
            alt="Quasar logo"
            src="https://cdn.quasar.dev/logo-v2/svg/logo.svg"
          />
        </q-avatar>
      </template>
    </q-input>

    <q-input
      standout
      bottom-slots
      v-model="text"
      label="Label"
      counter
      :dense="dense"
    >
      <template #prepend>
        <q-icon name="place" />
      </template>
      <template #append>
        <q-icon name="close" @click="text = ''" class="cursor-pointer" />
      </template>

      <template #hint> Field hint </template>
    </q-input>

    <q-input
      standout
      bottom-slots
      v-model="text"
      label="Label"
      counter
      maxlength="12"
      :dense="dense"
    >
      <template #before>
        <q-icon name="flight_takeoff" />
      </template>

      <template #append>
        <q-icon
          v-if="text !== ''"
          name="close"
          @click="text = ''"
          class="cursor-pointer"
        />
        <q-icon name="search" />
      </template>

      <template #hint> Field hint </template>
    </q-input>

    <q-input
      standout
      bottom-slots
      v-model="text"
      label="Label"
      counter
      maxlength="12"
      :dense="dense"
    >
      <template #before>
        <q-avatar>
          <img
            alt="User avatar"
            src="https://cdn.quasar.dev/img/avatar5.jpg"
          />
        </q-avatar>
      </template>

      <template #append>
        <q-icon
          v-if="text !== ''"
          name="close"
          @click="text = ''"
          class="cursor-pointer"
        />
        <q-icon name="schedule" />
      </template>

      <template #hint> Field hint </template>

      <template #after>
        <q-btn round dense flat icon="send" />
      </template>
    </q-input>

    <q-input
      standout
      bottom-slots
      v-model="text"
      label="Label"
      counter
      maxlength="12"
      :dense="dense"
    >
      <template #before>
        <q-icon name="event" />
      </template>

      <template #hint> Field hint </template>

      <template #append>
        <q-btn round dense flat icon="add" />
      </template>
    </q-input>

    <q-input standout v-model="text" hint="Disable" :dense="dense" disable />

    <q-input
      standout
      v-model="text"
      hint="Readonly"
      :dense="dense"
      readonly
    />

    <q-input
      standout
      v-model="text"
      hint="Disable and readonly"
      :dense="dense"
      disable
      readonly
    />
  </div>
</template>

<script setup>
import { ref } from 'vue'

const text = ref('')
const ph = ref('')
const dense = ref(false)
</script>

스탠드아웃(Standout) 디자인의 가장 어울리는 사용처 중 하나는 QToolbar 안이에요:

예시 "Standout in QToolbar":

<template>
  <div class="q-gutter-y-md column" style="width: 300px; max-width: 100%">
    <q-toolbar class="bg-primary text-white rounded-borders">
      <q-btn round dense flat icon="menu" class="q-mr-xs" />
      <q-avatar class="gt-xs">
        <img
          alt="Quasar logo"
          src="https://cdn.quasar.dev/logo-v2/svg/logo-mono-white.svg"
        />
      </q-avatar>

      <q-space />

      <q-input
        dark
        dense
        standout
        v-model="text"
        input-class="text-right"
        class="q-ml-md"
      >
        <template #append>
          <q-icon v-if="text === ''" name="search" />
          <q-icon
            v-else
            name="clear"
            class="cursor-pointer"
            @click="text = ''"
          />
        </template>
      </q-input>
    </q-toolbar>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const text = ref('')
</script>

보더리스 (Borderless)

borderless 디자인은 QInput이 스스로 테두리를 그리거나 배경색을 바꾸지 않고도 다른 컴포넌트에 자연스럽게 통합되게 해 줘요:

<template>
  <div class="q-gutter-y-md column" style="width: 300px; max-width: 100%">
    <q-toolbar class="bg-primary text-white rounded-borders">
      <q-btn round dense flat icon="menu" class="q-mr-xs" />
      <q-avatar class="gt-xs">
        <img
          alt="Quasar logo"
          src="https://cdn.quasar.dev/logo-v2/svg/logo-mono-white.svg"
        />
      </q-avatar>

      <q-space />

      <q-input
        dark
        borderless
        v-model="text"
        input-class="text-right"
        class="q-ml-md"
      >
        <template #append>
          <q-icon v-if="text === ''" name="search" />
          <q-icon
            v-else
            name="clear"
            class="cursor-pointer"
            @click="text = ''"
          />
        </template>
      </q-input>
    </q-toolbar>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const text = ref('')
</script>

둥근 디자인 (Rounded design)

rounded prop은 아래 예시에서 볼 수 있듯 Filled, Outlined, Standout 디자인에서만 동작해요:

예시 "Rounded":

<template>
  <div class="q-gutter-y-md column" style="max-width: 300px">
    <q-input rounded filled v-model="text">
      <template #prepend>
        <q-icon name="event" />
      </template>
    </q-input>

    <q-input rounded outlined v-model="text">
      <template #append>
        <q-avatar>
          <img
            alt="Quasar logo"
            src="https://cdn.quasar.dev/logo-v2/svg/logo.svg"
          />
        </q-avatar>
      </template>
    </q-input>

    <q-input
      rounded
      standout
      bottom-slots
      v-model="text"
      label="Label"
      counter
    >
      <template #prepend>
        <q-icon name="place" />
      </template>
      <template #append>
        <q-icon name="close" @click="text = ''" class="cursor-pointer" />
      </template>

      <template #hint> Field hint </template>
    </q-input>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const text = ref('')
</script>

네모 테두리 (Square borders)

square prop은 아래 예시에서 볼 수 있듯 Filled, Outlined, Standout 디자인에서만 의미가 있어요:

<template>
  <div class="q-gutter-y-md column" style="max-width: 300px">
    <q-input square filled v-model="text">
      <template #prepend>
        <q-icon name="event" />
      </template>
    </q-input>

    <q-input square outlined v-model="text">
      <template #append>
        <q-avatar>
          <img
            alt="Quasar logo"
            src="https://cdn.quasar.dev/logo-v2/svg/logo.svg"
          />
        </q-avatar>
      </template>
    </q-input>

    <q-input
      square
      standout
      bottom-slots
      v-model="text"
      label="Label"
      counter
    >
      <template #prepend>
        <q-icon name="place" />
      </template>
      <template #append>
        <q-icon name="close" @click="text = ''" class="cursor-pointer" />
      </template>

      <template #hint> Field hint </template>
    </q-input>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const text = ref('')
</script>

다크 모드 강제 적용 (Force dark mode)

<template>
  <div class="bg-grey-9 text-white">
    <div class="q-gutter-y-md column" style="max-width: 300px">
      <div>
        <q-toggle v-model="readonly" label="Readonly" dark />
        <q-toggle v-model="disable" label="Disable" dark />
      </div>

      <q-input dark v-model="text" :readonly="readonly" :disable="disable">
        <template #prepend>
          <q-icon name="event" />
        </template>
      </q-input>

      <q-input
        dark
        filled
        v-model="text"
        :readonly="readonly"
        :disable="disable"
      >
        <template #prepend>
          <q-icon name="event" />
        </template>
      </q-input>

      <q-input
        dark
        outlined
        v-model="text"
        :readonly="readonly"
        :disable="disable"
      >
        <template #append>
          <q-avatar>
            <img
              alt="Quasar logo"
              src="https://cdn.quasar.dev/logo-v2/svg/logo-dark.svg"
            />
          </q-avatar>
        </template>
      </q-input>

      <q-input
        dark
        standout
        bottom-slots
        v-model="text"
        label="Label"
        counter
        :readonly="readonly"
        :disable="disable"
      >
        <template #prepend>
          <q-icon name="place" />
        </template>
        <template #append>
          <q-icon name="close" @click="text = ''" class="cursor-pointer" />
        </template>

        <template #hint> Field hint </template>
      </q-input>

      <q-input
        dark
        borderless
        v-model="text"
        :readonly="readonly"
        :disable="disable"
      >
        <template #append>
          <q-icon name="search" />
        </template>
      </q-input>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const text = ref('')
const readonly = ref(false)
const disable = ref(false)
</script>

기본 기능 (Basic features)

네이티브 속성 (Native attributes)

API의 props 목록에 없는 QInput 속성들은 전부 네이티브 필드(input 또는 textarea)로 전달돼요. 예를 들면 autocomplete, placeholder 같은 것들이죠.

네이티브 속성에 대한 자세한 내용은 아래 자료를 확인해 주세요(input는 타입별 속성도 함께 확인해 보세요):

지우기 (Clearable)

도우미 기능으로 clearable prop을 쓰면 사용자가 추가된 아이콘을 통해 모델을 null로 초기화할 수 있어요. 아래 예시의 두 번째 QInput은 clearable을 직접 구현한 것과 같은 역할을 해요.

<template>
  <div class="q-gutter-y-md column" style="max-width: 300px">
    <q-input
      clearable
      filled
      color="purple-12"
      v-model="text"
      label="Label"
    />

    <!-- equivalent -->
    <q-input color="orange" filled v-model="text" label="Label">
      <template v-if="text" #append>
        <q-icon
          name="cancel"
          @click.stop.prevent="text = null"
          class="cursor-pointer"
        />
      </template>
    </q-input>

    <!-- clear-icon -->
    <q-input
      clearable
      clear-icon="close"
      filled
      color="purple-12"
      v-model="text"
      label="Label"
    />
  </div>
</template>

<script setup>
import { ref } from 'vue'

const text = ref('Some text')
</script>

입력 타입 (Input types)

아래 QInput들은 type prop을 사용해서 그 안에 네이티브에 해당하는 <input type="...">를 렌더링해요.

[!NOTE] 지원 여부와 동작은 전적으로 페이지를 렌더링하는 브라우저의 몫이에요. Quasar의 코어 코드가 관여하지 않아요.

<template>
  <div class="q-gutter-md row items-start">
    <q-input v-model="password" filled type="password" hint="Password" />

    <q-input
      v-model="password"
      filled
      :type="isPwd ? 'password' : 'text'"
      hint="Password with toggle"
    >
      <template #append>
        <q-icon
          :name="isPwd ? 'visibility_off' : 'visibility'"
          class="cursor-pointer"
          @click="isPwd = !isPwd"
        />
      </template>
    </q-input>

    <q-input v-model="email" filled type="email" hint="Email" />

    <q-input v-model="search" filled type="search" hint="Search">
      <template #append>
        <q-icon name="search" />
      </template>
    </q-input>

    <q-input v-model="tel" filled type="tel" hint="Telephone number" />

    <q-input v-model="url" filled type="url" hint="URL" />

    <q-input v-model="time" filled type="time" hint="Native time" />

    <q-input v-model="date" filled type="date" hint="Native date" />
  </div>
</template>

<script setup>
import { ref } from 'vue'

const password = ref('')
const isPwd = ref(true)
const email = ref('')
const search = ref('')
const tel = ref('')
const url = ref('')
const time = ref('')
const date = ref('')
</script>

[!TIP] date나 time 같은 일부 입력 타입은 항상 컨트롤을 렌더링해요. 그래서 label을 쓸 거라면 stack-label과 함께 설정하는 것이 좋아요. 그렇지 않으면 라벨이 브라우저 기본 컨트롤과 겹칠 수 있어요.

숫자 타입 입력 (Input of number type)

v-model.number(number 수식어에 주목)와 type="number" prop을 함께 사용하면 돼요:

<template>
  <q-input
    v-model.number="model"
    type="number"
    filled
    style="max-width: 200px"
  />
</template>

<script setup>
import { ref } from 'vue'

const model = ref(10)
</script>

파일 타입 입력 (Input of file type)

[!TIP] 대안 (ALTERNATIVES)

type="file"인 QInput 대신 QFile 피커나 QUploader를 쓰는 것이 좋을 수 있어요. 그래도 QInput을 쓰고 싶다면 아래 경고를 꼭 읽어 주세요.

[!WARNING] QInput이 type="file"일 때는 v-model을 사용하지 마세요. 브라우저 보안 정책이 그런 input에는 값을 설정하는 것을 허용하지 않아요. 그래서 읽기만 가능하고(@update:model-value 이벤트를 붙여서) 쓸 수는 없어요.

<template>
  <div class="q-gutter-md row items-start">
    <!--
      Due to browser security policy,
      we can only read the value, but not
      write to it, so we only have an @update:model-value listener
    -->

    <q-input
      @update:model-value="
        val => {
          file = val[0]
        }
      "
      filled
      type="file"
      hint="Native file"
    />

    <q-input
      @update:model-value="
        val => {
          files = val
        }
      "
      multiple
      filled
      type="file"
      hint="Native file (multiple)"
    />
  </div>
</template>

<script setup>
import { ref } from 'vue'

const file = ref(null)
const files = ref(null)
</script>

텍스트 영역 (Textarea)

<template>
  <div style="max-width: 300px">
    <q-input v-model="text" filled type="textarea" />
  </div>
</template>

<script setup>
import { ref } from 'vue'

const text = ref('')
</script>

textarea의 줄 간격은 font-size를 따르기 때문에, 네이티브 필드에 더 크거나 작은 글꼴을 주면(input-class나 input-style을 통해) 줄 간격이 고르게 유지돼요.

QInput이 내용에 맞춰 함께 커지길 원한다면 아래 예시처럼 autogrow prop을 사용하면 돼요:

예시 "Autogrow":

<template>
  <div style="max-width: 300px">
    <q-input v-model="text" filled autogrow />
  </div>
</template>

<script setup>
import { ref } from 'vue'

const text = ref('')
</script>

접두사와 접미사 (Prefix and suffix)

<template>
  <div class="q-gutter-y-md column" style="max-width: 300px">
    <q-input filled v-model="email" type="email" suffix="@gmail.com">
      <template #before>
        <q-icon name="mail" />
      </template>
    </q-input>

    <q-input outlined v-model.number="number" type="number" prefix="$">
      <template #append>
        <q-avatar>
          <img
            alt="Quasar logo"
            src="https://cdn.quasar.dev/logo-v2/svg/logo.svg"
          />
        </q-avatar>
      </template>
    </q-input>

    <q-input
      standout
      v-model="email"
      type="email"
      prefix="Email:"
      suffix="@gmail.com"
    >
      <template #prepend>
        <q-icon name="mail" />
      </template>
    </q-input>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const email = ref('')
const number = ref(null)
const text = ref('')
</script>

커스텀 라벨 (Custom Label)

label 슬롯을 사용하면 라벨의 모양을 커스터마이징하거나 QTooltip 같은 특별한 기능을 추가할 수 있어요.

[!IMPORTANT] label-slot 속성을 설정하는 것을 잊지 마세요.

라벨의 내용과 상호작용하려면(QTooltip) 슬롯 안의 요소에 all-pointer-events 클래스를 추가하세요.

<template>
  <div class="q-gutter-y-md column" style="max-width: 300px">
    <q-input
      filled
      v-model="email"
      suffix="@gmail.com"
      input-class="text-right"
      label-slot
      clearable
    >
      <template #label>
        <div class="row items-center all-pointer-events">
          <q-icon
            class="q-mr-xs"
            color="deep-orange"
            size="24px"
            name="mail"
          />
          Email (hover for more info)

          <q-tooltip
            class="bg-grey-8"
            anchor="top left"
            self="bottom left"
            :offset="[0, 8]"
            >Email address</q-tooltip
          >
        </div>
      </template>
    </q-input>

    <q-input outlined v-model="number" prefix="$" label-slot clearable>
      <template #prepend>
        <q-avatar>
          <img
            alt="Quasar logo"
            src="https://cdn.quasar.dev/logo-v2/svg/logo.svg"
          />
        </q-avatar>
      </template>

      <template #label>
        <span class="text-weight-bold text-deep-orange">You</span>
        can customize the
        <span
          class="q-px-sm bg-deep-orange text-white text-italic rounded-borders"
          >label</span
        >
      </template>
    </q-input>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const email = ref('john.doe')
const number = ref(123)
</script>

섀도 텍스트 (Shadow text)

<template>
  <div class="q-gutter-y-md column" style="max-width: 300px">
    <q-input
      v-model="inputModel"
      filled
      clearable
      color="purple-12"
      label="Input with shadow text"
      hint="Press TAB to autocomplete suggested value or ESC to cancel suggestion"
      :shadow-text="inputShadowText"
      @keydown="processInputFill"
      @focus="processInputFill"
    />

    <q-input
      v-model="textareaModel"
      filled
      clearable
      autogrow
      color="green-8"
      label="Autogrow textarea with shadow text"
      hint="Press TAB to autocomplete suggested value or ESC to cancel suggestion"
      :shadow-text="textareaShadowText"
      @keydown="processTextareaFill"
      @focus="processTextareaFill"
    />

    <q-input
      v-model="textareaModel"
      filled
      clearable
      type="textarea"
      color="red-12"
      label="Textarea with shadow text"
      hint="Press TAB to autocomplete suggested value or ESC to cancel suggestion"
      :shadow-text="textareaShadowText"
      @keydown="processTextareaFill"
      @focus="processTextareaFill"
    />
  </div>
</template>

<script setup>
import { event } from 'quasar'
import { computed, ref } from 'vue'

const { stopAndPrevent } = event

const inputModel = ref('')
const inputFillCancelled = ref(false)
const inputShadowText = computed(() => {
  if (inputFillCancelled.value) return ''

  const t = 'Text filled when you press TAB'
  const empty =
    typeof inputModel.value !== 'string' || inputModel.value.length === 0

  if (empty) {
    return t
  } else if (t.indexOf(inputModel.value) !== 0) {
    return ''
  }

  return t.split(inputModel.value).slice(1).join(inputModel.value)
})

const textareaModel = ref('')
const textareaFillCancelled = ref(false)
const textareaShadowText = computed(() => {
  if (textareaFillCancelled.value) {
    return ''
  }

  const t = 'This text\nwill be filled\non multiple lines\nwhen you press TAB',
    empty =
      typeof textareaModel.value !== 'string' ||
      textareaModel.value.length === 0

  if (empty) {
    return t.split('\n')[0]
  } else if (t.indexOf(textareaModel.value) !== 0) {
    return ''
  }

  return t
    .split(textareaModel.value)
    .slice(1)
    .join(textareaModel.value)
    .split('\n')[0]
})

function processInputFill(e) {
  if (e === void 0) return

  if (e.keyCode === 27) {
    if (inputFillCancelled.value !== true) {
      inputFillCancelled.value = true
    }
  } else if (e.keyCode === 9) {
    if (
      inputFillCancelled.value !== true &&
      inputShadowText.value.length !== 0
    ) {
      stopAndPrevent(e)
      inputModel.value =
        (typeof inputModel.value === 'string' ? inputModel.value : '') +
        inputShadowText.value
    }
  } else if (inputFillCancelled.value) {
    inputFillCancelled.value = false
  }
}

function processTextareaFill(e) {
  if (e === void 0) return

  if (e.keyCode === 27) {
    if (!textareaFillCancelled.value) {
      textareaFillCancelled.value = true
    }
  } else if (e.keyCode === 9) {
    if (!textareaFillCancelled.value && textareaShadowText.value.length !== 0) {
      stopAndPrevent(e)
      textareaModel.value =
        (typeof textareaModel.value === 'string' ? textareaModel.value : '') +
        textareaShadowText.value
    }
  } else if (textareaFillCancelled.value) {
    textareaFillCancelled.value = false
  }
}
</script>

"submit" 타입 QBtn과 슬롯 (Slots with QBtn type "submit")

[!IMPORTANT] QField, QInput, QSelect의 "before", "after", "prepend", "append" 슬롯 중 하나에 type="submit"인 QBtn을 넣는다면, 해당 QBtn에 @click 리스너도 추가해야 해요. 이 리스너는 폼을 제출하는 메서드를 호출해야 해요. 그런 슬롯 안의 모든 "click" 이벤트는 부모 요소로 전파되지 않아요.

모델 디바운싱 (Debouncing model)

디바운싱의 역할은 모델을 감시하면서 무거운 작업을 할 때 유용해요. 매 키 입력마다 모델을 업데이트하지 말고, 사용자가 먼저 입력을 끝내도록 두었다가 모델 업데이트를 트리거하고 싶을 때 쓰죠.

예시 "Debounce model":

<template>
  <div style="max-width: 350px">
    <div class="q-gutter-md">
      <div>
        <q-badge color="teal">Model: "{{ search }}"</q-badge>
      </div>

      <q-input
        v-model="search"
        debounce="500"
        filled
        placeholder="Search"
        hint="Debouncing 500ms"
      >
        <template #append>
          <q-icon name="search" />
        </template>
      </q-input>

      <q-input
        v-model="search"
        debounce="1000"
        filled
        placeholder="Search"
        hint="Debouncing 1000ms"
      >
        <template #append>
          <q-icon name="search" />
        </template>
      </q-input>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const search = ref('')
</script>

모델 지연 업데이트 (Lazy model update)

모델을 사용자가 편집을 끝낸 후(네이티브 change 이벤트 또는 입력이 포커스를 잃을 때)에만 업데이트하고 싶다면 v-model.lazy 수식어를 사용하세요. 네이티브 <input>에서의 수식어 동작과 같아요. 이 수식어를 쓰는 동안에는 debounce prop이 무시돼요.

예시 "Lazy model":

<template>
  <div style="max-width: 350px">
    <div class="q-gutter-md">
      <div>
        <q-badge color="teal">Model: "{{ name }}"</q-badge>
      </div>

      <q-input
        v-model.lazy="name"
        filled
        placeholder="Type, then hit Enter or move focus away"
        hint="Updates the model on change only"
      />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const name = ref('')
</script>

로딩 상태 (Loading state)

<template>
  <div class="q-gutter-y-md column" style="max-width: 300px">
    <q-input :loading="loadingState" filled v-model="text" label="Label" />
    <q-toggle v-model="loadingState" label="Loading state" />
  </div>
</template>

<script setup>
import { ref } from 'vue'

const text = ref('')
const loadingState = ref(false)
</script>

마스크 (Mask)

mask prop을 사용하면 사용자가 특정 형식으로 입력하도록 강제하거나 도와줄 수 있어요.

[!NOTE] 마스크는 type이 'text'(기본값), 'search', 'url', 'tel', 'password' 중 하나일 때만 사용할 수 있어요.

[!WARNING] maxlength과의 상호작용

마스크는 이미 자체 슬롯에서 입력 길이를 제한해요. 그래서 maxlength prop과 함께 쓰면 안 돼요. 네이티브 maxlength는 표시되는 전체 값(리터럴과 채움 문자 포함)을 세기 때문에, 마스크 전체 길이보다 작은 값은 입력을 너무 일찍 차단하게 돼요. fill-mask를 쓰면 표시되는 값이 항상 마스크의 전체 길이라서 그런 maxlength는 필드를 아예 잠가 버려요.

아래는 기본 마스크 토큰이에요. 자신만의 토큰을 추가하려면 다음 섹션을 보세요.

토큰 설명
# 숫자 (Numeric)
S a~z 문자, 대소문자 무관 (Letter, case insensitive)
N 영숫자, 문자는 대소문자 무관 (Alphanumeric, case insensitive)
A 문자, 대문자로 변환 (Letter, uppercase)
a 문자, 소문자로 변환 (Letter, lowercase)
X 영숫자, 문자는 대문자로 변환 (Alphanumeric, uppercase)
x 영숫자, 문자는 소문자로 변환 (Alphanumeric, lowercase)

QInput mask prop에는 헬퍼가 있어요: 전체 목록. 편의상 사용하면 돼요("phone", "card" 같은 예시) 아니면 커스텀 요구에 맞는 문자열을 직접 작성해도 돼요.

예시 "Basic Mask":

<template>
  <div style="max-width: 300px">
    <div class="q-gutter-md">
      <q-input
        filled
        v-model="id"
        label="Special ID"
        mask="###/##"
        hint="Mask: ###/##"
      />

      <q-input
        filled
        v-model="phone"
        label="Phone"
        mask="(###) ### - ####"
        hint="Mask: (###) ### - ####"
      />

      <q-input
        filled
        v-model="serialNumber"
        label="Serial number"
        mask="AAAA - #### - #### - SSS"
        hint="Mask: AAAA - #### - #### - SSS"
      />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const id = ref(null)
const phone = ref(null)
const serialNumber = ref(null)
</script>

예시 "Filling the mask":

<template>
  <div style="max-width: 300px">
    <div class="q-gutter-md">
      <q-input
        filled
        v-model="id"
        label="Special ID"
        mask="###/##"
        fill-mask
        hint="Mask: ###/##"
      />

      <q-input
        filled
        v-model="phone"
        label="Phone"
        mask="(###) ### - ####"
        fill-mask
        hint="Mask: (###) ### - ####"
      />

      <q-input
        filled
        v-model="card"
        label="Card"
        mask="#### #### #### ####"
        fill-mask="#"
        hint="Mask: #### #### #### ####, FillMask: #"
      />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const id = ref(null)
const phone = ref(null)
const card = ref(null)
</script>

마스크 자체의 키 처리 — 마스크 리터럴 위의 커서 이동과 BACKSPACE / DELETE 경계 로직 — 를 방지하려면 그 keydown 이벤트를 막으면 돼요. 이때 브라우저의 해당 키 기본 처리도 함께 취소된다는 점을 기억하세요. 그래서 @keydown.left.prevent는 커서를 리터럴 너머로 옮기는 대신 그 자리에 유지하고, 재위치시키는 것은 여러분의 핸들러 몫이에요.

unmasked-value는 예를 들어 사용자에게 특정 형식으로 입력하도록 강제하고 싶지만, 모델에는 원시(raw) 값을 담고 싶을 때 유용해요:

예시 "Unmasked model":

<template>
  <div style="max-width: 300px">
    <div class="q-gutter-md">
      <q-badge color="secondary">Id model: "{{ id }}"</q-badge>
      <q-input
        filled
        v-model="id"
        label="Special Id"
        mask="###/##"
        unmasked-value
        hint="Mask: ###/##"
      />

      <q-badge color="secondary">Phone model: "{{ phone }}"</q-badge>
      <q-input
        filled
        v-model="phone"
        label="Phone"
        mask="(###) ### - ####"
        unmasked-value
        hint="Mask: (###) ### - ####"
      />

      <q-badge color="secondary">Card model: "{{ card }}"</q-badge>
      <q-input
        filled
        v-model="card"
        label="Card"
        mask="#### - #### - #### - ####"
        fill-mask="#"
        unmasked-value
        hint="Mask: #### - #### - #### - ####, FillMask: #"
      />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const id = ref(null)
const phone = ref(null)
const card = ref(null)
</script>

reverse-fill-mask는 사용자가 마스크를 끝에서부터 채우도록 강제하고 고정되지 않은 입력 길이를 허용하고 싶을 때 유용해요:

예시 "Filling the mask in reverse":

<template>
  <div style="max-width: 300px">
    <div class="q-gutter-md">
      <q-input
        filled
        v-model="price"
        label="Price with 2 decimals"
        mask="#.##"
        fill-mask="0"
        reverse-fill-mask
        hint="Mask: #.##"
        input-class="text-right"
      />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const price = ref(null)
</script>

여러 마스크 (Multiple masks)

하나의 필드가 여러 형식을 받아야 할 때(예: 지역 번호 8자리 또는 9자리 전화번호) mask를 값의 길이로 형식을 고르는 computed 속성에 바인딩하세요. 패턴을 안정적으로 만드는 두 가지 세부 사항이 있어요: unmasked-value를 사용해서 현재 적용된 마스크의 리터럴과 무관하게 순수한 숫자 길이가 판단을 좌우하게 하고, 짧은 마스크 끝에 여분의 토큰 하나를 남겨 임계값을 넘는 숫자가 입력될 수 있게 하는 거죠. 그 숫자가 들어오는 순간 computed 속성이 마스크를 전환하고 값을 다시 배치하는데, 커서는 그 자리에 유지돼요.

<template>
  <div style="max-width: 300px">
    <div class="q-gutter-md">
      <q-badge color="secondary">Model: "{{ phone }}"</q-badge>

      <q-input
        filled
        v-model="phone"
        label="Phone (BR)"
        :mask="phoneMask"
        unmasked-value
        hint="8 digits: (##) ####-####, 9 digits: (##) #####-####"
      />
    </div>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue'

const phone = ref('')

// Brazilian landlines have 8 local digits, mobiles 9; pick the mask
// from the unmasked length. Keeping the model unmasked (unmasked-value)
// is what makes this reliable: the plain digit count decides, unaffected
// by the literals of whichever mask is currently applied.
const phoneMask = computed(() =>
  phone.value !== null && phone.value.length > 10
    ? '(##) #####-####'
    : '(##) ####-#####'
)
</script>

커스텀 마스크 토큰 (Custom mask tokens) (v2.18.4+)

기본 토큰 위에 커스텀 마스크 토큰을 정의하거나, 기본 토큰의 일부/전부를 덮어쓸 수도 있어요.

커스텀 마스크 토큰은 기본 토큰과 같은 문법이어야 해요. transform 속성은 선택 사항이라는 점을 기억하세요.

예시 "Custom tokens":

<template>
  <div style="max-width: 300px">
    <div class="q-gutter-md">
      <q-input
        filled
        v-model="id"
        label="Special ID"
        mask="AA-CC-XX-CC"
        :mask-tokens="customTokens"
        hint="Mask: AA-CC-XX-CC, example: BC-12-56-E2"
      />

      <div>C (0-4a-eA-E to uppercase), X override (5-8)</div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const id = ref(null)
const customTokens = {
  C: {
    pattern: '[0-4a-eA-E]',
    negate: '[^0-4a-eA-E]',
    transform: v => v.toLocaleUpperCase()
  },
  X: { pattern: '[5-8]', negate: '[^5-8]' }
}
</script>

서드파티 마스크 프로세서 사용 (Using third party mask processors)

QInput을 약간만 조정하면 쉽게 어떤 서드파티 마스크 프로세서든 사용할 수 있어요.

이런 QInput에서 시작해 볼게요:

<q-input
  filled
  v-model="price"
  label="Price with 2 decimals"
  mask="#.##"
  fill-mask="#"
  reverse-fill-mask
  hint="Mask: #.00"
  input-class="text-right"
/>

v-money 디렉티브를 사용할 수 있어요:

<q-field
  filled
  v-model="price"
  label="Price with v-money directive"
  hint="Mask: $ #,###.00 #"
>
  <template #control="{ id, floatingLabel, modelValue, emitValue }">
    <input
      :id="id"
      class="q-field__input text-right"
      :value="modelValue"
      @change="e => emitValue(e.target.value)"
      v-money="moneyFormatForDirective"
      v-show="floatingLabel"
    />
  </template>
</q-field>
moneyFormatForDirective: {
  decimal: '.',
  thousands: ',',
  prefix: '$ ',
  suffix: ' #',
  precision: 2,
  masked: false /* doesn't work with directive */
}

또는 money 컴포넌트를 사용할 수 있어요:

<q-field
  filled
  v-model="price"
  label="Price with v-money component"
  hint="Mask: $ #,###.00 #"
>
  <template #control="{ id, floatingLabel, modelValue, emitValue }">
    <money
      :id="id"
      class="q-field__input text-right"
      :model-value="modelValue"
      @update:model-value="emitValue"
      v-bind="moneyFormatForComponent"
      v-show="floatingLabel"
    />
  </template>
</q-field>
moneyFormatForComponent: {
  decimal: '.',
  thousands: ',',
  prefix: '$ ',
  suffix: ' #',
  precision: 2,
  masked: true
}

검증 (Validation)

내부 검증 (Internal validation)

:rules prop으로 QInput 컴포넌트를 검증할 수 있어요. 내장 규칙의 배열이나 여러분만의 검증 함수를 지정하세요. 커스텀 검증 함수는 검증이 성공하면 true를, 성공하지 않으면 오류 메시지가 담긴 String을 반환해요.

[!NOTE] 기본적으로 성능 이유로 규칙(rules)이 바뀌어도 모델이 바뀌기 전까지는 새 검증을 트리거하지 않아요. 규칙이 바뀔 때도 검증을 트리거하려면 reactive-rules Boolean prop을 사용하세요. 단점은 성능 저하(정말 필요할 때만 쓰세요!)가 있고, rules의 값을 computed prop으로 지정(템플릿에 인라인으로 지정하지 않고)하면 어느 정도 완화할 수 있어요.

이렇게 하면 다음과 같은 편리한 규칙 형태를 작성할 수 있어요:

value => condition || errorMessage

// example:
value => value.includes('Hello') || 'Field must contain word Hello'

QInput에서 resetValidation() 메서드를 호출하면 검증을 초기화할 수 있어요.

QInput rules prop에는 헬퍼가 있어요: 전체 목록. 편의상 사용하면 돼요("date", "time", "hexColor", "rgbOrRgbaColor", "anyColor" 같은 예시) 아니면 커스텀 요구에 맞는 문자열을 직접 작성해도 돼요.

[!WARNING] 네이티브 제약은 rules와 별개예요

네이티브 HTML 제약("email"이나 "url" 같은 type, 또는 네이티브 input으로 전달되는 pattern/required 속성)은 브라우저가 네이티브 폼 제출 시에만 강제해요. 프로그래매틱 validate() 메서드(QInput 또는 이를 감싼 QForm에서)는 rules만 평가하고 그 제약을 참조하지 않아요. validate()가 잡아야 하는 제약은 rules로도 표현하세요. 예: :rules="['email']".

예시 "Validation required":

<template>
  <div style="max-width: 300px">
    <q-input
      ref="inputRef"
      filled
      v-model="model"
      label="Required Field"
      :rules="[val => !!val || 'Field is required']"
    />

    <q-btn
      class="q-mt-sm"
      label="Reset Validation"
      @click="reset"
      color="primary"
    />
  </div>
</template>

<script setup>
import { ref, useTemplateRef } from 'vue'

const inputRef = useTemplateRef('inputRef')
const model = ref('')

function reset() {
  inputRef.value.resetValidation()
}
</script>

예시 "Maximum length":

<template>
  <div style="max-width: 300px">
    <q-input
      ref="inputRef"
      filled
      v-model="model"
      label="Maximum 3 characters"
      :rules="[val => val.length <= 3 || 'Please use maximum 3 characters']"
    />

    <q-btn
      class="q-mt-sm"
      label="Reset Validation"
      @click="reset"
      color="primary"
    />
  </div>
</template>

<script setup>
import { ref, useTemplateRef } from 'vue'

const inputRef = useTemplateRef('inputRef')
const model = ref('')

function reset() {
  inputRef.value.resetValidation()
}
</script>

lazy-rules를 설정하면 필드가 포커스를 잃을 때 검증이 트리거돼요(readonly 필드도 포함, 오직 disable된 필드만 검증에서 제외). 오류가 표시되는 동안에는 값이 유효해지는 즉시 오류가 사라지도록 매 변경마다 재검증해요. 필드 안에서 연 메뉴나 다이얼로그(예: append 슬롯의 QPopupProxy)는 열려 있는 동안 필드의 포커스를 유지하므로 포커스 손실로 치지 않아요. lazy-rules가 ondemand 문자열로 설정되면 컴포넌트의 validate() 메서드가 수동으로 호출되거나 감싸는 QForm이 스스로 제출할 때만 검증이 트리거돼요.

예시 "Lazy rules":

<template>
  <div style="max-width: 300px">
    <q-input
      ref="inputRef"
      filled
      v-model="model"
      label="Required field with length < 2"
      hint="Validation starts after first blur"
      counter
      :rules="[
        val => !!val || '* Required',
        val => val.length < 2 || 'Please use maximum 1 character'
      ]"
      lazy-rules
    />

    <q-btn
      class="q-mt-sm"
      label="Reset Validation"
      @click="reset"
      color="primary"
    />
  </div>
</template>

<script setup>
import { ref, useTemplateRef } from 'vue'

const inputRef = useTemplateRef('inputRef')
const model = ref('')

function reset() {
  inputRef.value.resetValidation()
}
</script>

예시 "Form validation":

<template>
  <div style="max-width: 300px">
    <form
      @submit.prevent.stop="onSubmit"
      @reset.prevent.stop="onReset"
      class="q-gutter-md"
    >
      <q-input
        ref="nameRef"
        filled
        v-model="name"
        label="Your name *"
        hint="Name and surname"
        lazy-rules
        :rules="nameRules"
      />

      <q-input
        ref="ageRef"
        filled
        type="number"
        v-model.number="age"
        label="Your age *"
        lazy-rules
        :rules="ageRules"
      />

      <q-toggle v-model="accept" label="I accept the license and terms" />

      <div>
        <q-btn label="Submit" type="submit" color="primary" />
        <q-btn
          label="Reset"
          type="reset"
          color="primary"
          flat
          class="q-ml-sm"
        />
      </div>
    </form>
  </div>
</template>

<script setup>
import { useQuasar } from 'quasar'
import { ref, useTemplateRef } from 'vue'

const $q = useQuasar()

const name = ref(null)
const nameRef = useTemplateRef('nameRef')
const nameRules = [val => (val && val.length !== 0) || 'Please type something']

const age = ref(null)
const ageRef = useTemplateRef('ageRef')
const ageRules = [
  val => (val !== null && val !== '') || 'Please type your age',
  val => (val > 0 && val < 100) || 'Please type a real age'
]

const accept = ref(false)

function onSubmit() {
  nameRef.value.validate()
  ageRef.value.validate()

  if (nameRef.value.hasError || ageRef.value.hasError) {
    // form has error
  } else if (accept.value !== true) {
    $q.notify({
      color: 'negative',
      message: 'You need to accept the license and terms first'
    })
  } else {
    $q.notify({
      icon: 'done',
      color: 'positive',
      message: 'Submitted'
    })
  }
}

function onReset() {
  name.value = null
  age.value = null

  nameRef.value.resetValidation()
  ageRef.value.resetValidation()
}
</script>

비동기 규칙 (Async rules)

또한 async/await를 사용하거나 Promise를 직접 반환해서 규칙을 비동기로 만들 수도 있어요. 비동기 검증이 진행 중인 동안 값이 바뀌거나 필드가 블러되면, 검증이 끝나는 시점에 재검증해서 표시되는 판정이 항상 현재 값과 일치하게 해요.

[!TIP] async 규칙과 debounce prop을 함께 쓰는 것을 고려해 보세요. 매 키 입력마다 비동기 규칙을 즉시 호출하면 성능에 좋지 않을 수 있어요.

<template>
  <div style="max-width: 300px">
    <q-input
      ref="inputRef"
      filled
      v-model="model"
      label="Required Field *"
      :rules="[myRule]"
    />

    <q-btn
      class="q-mt-sm"
      label="Reset Validation"
      @click="reset"
      color="primary"
    />
  </div>
</template>

<script setup>
import { ref, useTemplateRef } from 'vue'

const inputRef = useTemplateRef('inputRef')
const model = ref('')

function myRule(val) {
  // simulating a delay

  return new Promise(resolve => {
    setTimeout(() => {
      // call
      //  resolve(true)
      //     --> content is valid
      //  resolve(false)
      //     --> content is NOT valid, no error message
      //  resolve(error_message)
      //     --> content is NOT valid, we have error message
      resolve(Boolean(val) || '* Required')

      // calling reject(...) will also mark the input
      // as having an error, but there will not be any
      // error message displayed below the input
      // (only in browser console)
    }, 1000)
  })
}

function reset() {
  inputRef.value.resetValidation()
}
</script>

외부 검증 (External validation)

외부 검증을 사용해서 error와 error-message만 전달할 수도 있어요(bottom-slots를 활성화해서 오류 메시지를 표시하세요).

[!TIP] 필요에 따라 Regle(우리가 추천하는 방식)이나 다른 검증 라이브러리를 QInput에 연결할 수 있어요.

예시 "External":

<template>
  <div style="max-width: 300px">
    <q-input
      filled
      v-model="model"
      label="Type here"
      bottom-slots
      hint="Max 3 characters"
      error-message="Please use maximum 3 characters"
      :error="!isValid"
    />
  </div>
</template>

<script setup>
import { computed, ref } from 'vue'

const model = ref('')
const isValid = computed(() => model.value.length <= 3)
</script>

오류 메시지용 슬롯도 커스터마이징할 수 있어요:

예시 "Slot for error message":

<template>
  <div style="max-width: 300px">
    <q-input
      filled
      v-model="model"
      label="Type here"
      bottom-slots
      :error="!isValid"
      hint="Max 3 characters"
    >
      <template #error> Please use maximum 3 characters. </template>
    </q-input>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue'

const model = ref('')
const isValid = computed(() => model.value.length <= 3)
</script>

접근성 (Accessibility) (v2.25+)

QInput은 QField 프레임 안에 네이티브 <input>(또는 <textarea>)을 렌더링해요. 그래서 QField의 접근성 섹션에서 설명한 모든 것이 여기에도 적용돼요: 생성된 SSR-safe id를 통한 라벨 연결, role="alert"로 알리는 오류 메시지와 aria-invalid/aria-errormessage/aria-describedby를 통한 컨트롤 참조, 그리고 키보드로 조작 가능한 지우기 버튼이죠.

label prop은 네이티브 요소에 aria-label로도 노출돼요 — 여러분이 직접 설정한 aria-label이나 aria-labelledby 속성이 우선해요 — 그리고 disable과 readonly는 네이티브 disabled와 readonly 속성에 매핑돼요(readonly input은 Tab 순서에 그대로 남고 도달했을 때 필드의 포커스 상태를 보여주며, QField 페이지에 설명된 대로예요). 그 외의 네이티브 속성(placeholder, autocomplete, inputmode, ...)도 네이티브 요소로 흘러내려가요.

네이티브 폼 제출 (Native form submit)

action과 method가 있는 네이티브 폼을 다룰 때(예: Quasar를 ASP.NET 컨트롤러와 함께 쓸 때) QInput에 name 속성을 지정해야 해요. 그렇지 않으면 formData에 포함되지 않을 수 있어요:

예시 "Native form":

<template>
  <q-form @submit="onSubmit" class="q-gutter-md">
    <q-input
      name="name"
      autocomplete="name"
      v-model="name"
      color="primary"
      label="Full name"
      filled
      clearable
    />

    <div>
      <q-btn label="Submit" type="submit" color="primary" />
    </div>
  </q-form>

  <q-card
    v-if="submitResult.length > 0"
    flat
    bordered
    class="q-mt-md"
    :class="$q.dark.isActive ? 'bg-grey-9' : 'bg-grey-2'"
  >
    <q-card-section
      >Submitted form contains the following formData (key =
      value):</q-card-section
    >
    <q-separator />
    <q-card-section class="row q-gutter-sm items-center">
      <div
        v-for="(item, index) in submitResult"
        :key="index"
        class="q-px-sm q-py-xs bg-grey-8 text-white rounded-borders text-center text-no-wrap"
        >{{ item.name }} = {{ item.value }}</div
      >
    </q-card-section>
  </q-card>
</template>

<script setup>
import { ref } from 'vue'

const submitResult = ref([])
const name = ref('Jane Doe')

function onSubmit(evt) {
  const formData = new FormData(evt.target)
  const data = []

  for (const [key, value] of formData.entries()) {
    data.push({
      name: key,
      value
    })
  }

  submitResult.value = data
}
</script>

더 알아보기 (Learn more)