이온 입력 OTP (ion-input-otp)
ion-input-otp는 일회용 비밀번호(OTP) 입력을 위한 특수 입력 컴포넌트예요. 여러 개의 입력 상자와 자동 포커스 관리를 지원해서, 인증 코드 입력 UI를 만드는 데 아주 편리하죠.
출처: 문서
본문
Encapsulation: scoped
Input OTP 컴포넌트는 일회용 비밀번호(OTP)를 입력하기 위해 설계된 특수한 입력 컴포넌트입니다. 여러 개의 입력 상자와 자동 포커스 관리 기능을 지원하는, 인증 코드 입력을 위한 사용자 친화적인 인터페이스를 제공합니다.
기본 사용법 (Basic Usage)
이 컴포넌트는 기본적으로 4개의 입력 상자를 제공하며, 이는 많은 인증 코드에서 흔히 쓰이는 길이입니다. 입력 상자의 개수는 length 속성으로 사용자 정의할 수 있습니다.
JavaScript
<ion-input-otp> Didn't get a code? <a href="#">Resend the code</a> </ion-input-otp>
<ion-input-otp length="6"> Didn't get a code? <a href="#">Resend the code</a> </ion-input-otp>
Angular
src/app/example.component.html
<ion-input-otp> Didn't get a code? <a href="#">Resend the code</a> </ion-input-otp>
<ion-input-otp length="6"> Didn't get a code? <a href="#">Resend the code</a> </ion-input-otp>
src/app/example.component.ts
import { Component } from '@angular/core';
import { IonInputOtp } from '@ionic/angular';
@Component({
selector: 'app-example',
templateUrl: 'example.component.html',
styleUrls: ['example.component.css'],
imports: [IonInputOtp],
})
export class ExampleComponent {}
React
import React from 'react';
import { IonInputOtp } from '@ionic/react';
function Example() {
return (
<>
<IonInputOtp>
Didn't get a code? <a href="#">Resend the code</a>
</IonInputOtp>
<IonInputOtp length="6">
Didn't get a code? <a href="#">Resend the code</a>
</IonInputOtp>
</>
);
}
export default Example;
Vue
<template>
<ion-input-otp> Didn't get a code? <a href="#">Resend the code</a> </ion-input-otp>
<ion-input-otp length="6"> Didn't get a code? <a href="#">Resend the code</a> </ion-input-otp>
</template>
<script setup lang="ts">
import { IonInputOtp } from '@ionic/vue';
</script>
타입 (Type)
type 속성은 입력 형식을 결정하며, 숫자 또는 영숫자(alphanumeric) 인증 코드를 지원합니다. 두 가지 값인 number와 text를 받을 수 있습니다. 기본적으로 숫자 인증 코드를 입력하기 위해 type="number"를 사용합니다. type="text"를 지정하면 영숫자 입력을 허용합니다. 이렇게 유연하기 때문에 숫자 전용 코드(예: SMS 인증 코드)나 영숫자 코드(예: 백업 코드나 복구 키)처럼 서로 다른 OTP 형식을 처리할 수 있습니다.
type 속성은 inputmode와 pattern 속성을 모두 자동으로 설정합니다:
type="number"일 때:- 모바일 기기에서 숫자 키보드가 표시되도록
inputmode="numeric"을 설정합니다 - 숫자 입력만 허용하도록
pattern="[\p{N}]"을 설정합니다 type="text"일 때:- 표준 키보드가 표시되도록
inputmode="text"를 설정합니다 - 영숫자 입력을 허용하도록
pattern="[\p{L}\p{N}]"을 설정합니다 패턴 검증과 사용자 정의에 대한 더 자세한 내용은 Pattern 섹션을 참고하세요.
JavaScript
<ion-input-otp> Numbers only </ion-input-otp> <ion-input-otp type="text"> Letters and numbers </ion-input-otp>
Angular
src/app/example.component.html
<ion-input-otp> Numbers only </ion-input-otp> <ion-input-otp type="text"> Letters and numbers </ion-input-otp>
src/app/example.component.ts
import { Component } from '@angular/core';
import { IonInputOtp } from '@ionic/angular';
@Component({
selector: 'app-example',
templateUrl: 'example.component.html',
styleUrls: ['example.component.css'],
imports: [IonInputOtp],
})
export class ExampleComponent {}
React
import React from 'react';
import { IonInputOtp } from '@ionic/react';
function Example() {
return (
<>
<IonInputOtp> Numbers only </IonInputOtp>
<IonInputOtp type="text"> Letters and numbers </IonInputOtp>
</>
);
}
export default Example;
Vue
<template>
<ion-input-otp> Numbers only </ion-input-otp>
<ion-input-otp type="text"> Letters and numbers </ion-input-otp>
</template>
<script setup lang="ts">
import { IonInputOtp } from '@ionic/vue';
</script>
모양 (Shape)
shape 속성은 입력 상자의 테두리 반경(border radius)을 제어하여 둥글거나 각진 모서리를 만듭니다.
JavaScript
<ion-input-otp shape="round"> Round </ion-input-otp>
<ion-input-otp shape="soft"> Soft </ion-input-otp>
<ion-input-otp shape="rectangular"> Rectangular </ion-input-otp>
Angular
src/app/example.component.html
<ion-input-otp shape="round"> Round </ion-input-otp>
<ion-input-otp shape="soft"> Soft </ion-input-otp>
<ion-input-otp shape="rectangular"> Rectangular </ion-input-otp>
src/app/example.component.ts
import { Component } from '@angular/core';
import { IonInputOtp } from '@ionic/angular';
@Component({
selector: 'app-example',
templateUrl: 'example.component.html',
styleUrls: ['example.component.css'],
imports: [IonInputOtp],
})
export class ExampleComponent {}
React
import React from 'react';
import { IonInputOtp } from '@ionic/react';
function Example() {
return (
<>
<IonInputOtp shape="round"> Round </IonInputOtp>
<IonInputOtp shape="soft"> Soft </IonInputOtp>
<IonInputOtp shape="rectangular"> Rectangular </IonInputOtp>
</>
);
}
export default Example;
Vue
<template>
<ion-input-otp shape="round"> Round </ion-input-otp>
<ion-input-otp shape="soft"> Soft </ion-input-otp>
<ion-input-otp shape="rectangular"> Rectangular </ion-input-otp>
</template>
<script setup lang="ts">
import { IonInputOtp } from '@ionic/vue';
</script>
채우기 (Fill)
fill 속성은 입력 상자의 배경 스타일을 제어하며, 테두리(bordered) 또는 채워진(filled) 배경을 제공합니다.
JavaScript
<ion-input-otp fill="outline"> Outline </ion-input-otp> <ion-input-otp fill="solid"> Solid </ion-input-otp>
Angular
src/app/example.component.html
<ion-input-otp fill="outline"> Outline </ion-input-otp> <ion-input-otp fill="solid"> Solid </ion-input-otp>
src/app/example.component.ts
import { Component } from '@angular/core';
import { IonInputOtp } from '@ionic/angular';
@Component({
selector: 'app-example',
templateUrl: 'example.component.html',
styleUrls: ['example.component.css'],
imports: [IonInputOtp],
})
export class ExampleComponent {}
React
import React from 'react';
import { IonInputOtp } from '@ionic/react';
function Example() {
return (
<>
<IonInputOtp fill="outline"> Outline </IonInputOtp>
<IonInputOtp fill="solid"> Solid </IonInputOtp>
</>
);
}
export default Example;
Vue
<template>
<ion-input-otp fill="outline"> Outline </ion-input-otp>
<ion-input-otp fill="solid"> Solid </ion-input-otp>
</template>
<script setup lang="ts">
import { IonInputOtp } from '@ionic/vue';
</script>
크기 (Size)
size 속성은 입력 상자에 대한 다양한 크기 옵션을 제공합니다.
JavaScript
<ion-input-otp size="small"> Small </ion-input-otp>
<ion-input-otp size="medium"> Medium </ion-input-otp>
<ion-input-otp size="large"> Large </ion-input-otp>
Angular
src/app/example.component.html
<ion-input-otp size="small"> Small </ion-input-otp>
<ion-input-otp size="medium"> Medium </ion-input-otp>
<ion-input-otp size="large"> Large </ion-input-otp>
src/app/example.component.ts
import { Component } from '@angular/core';
import { IonInputOtp } from '@ionic/angular';
@Component({
selector: 'app-example',
templateUrl: 'example.component.html',
styleUrls: ['example.component.css'],
imports: [IonInputOtp],
})
export class ExampleComponent {}
React
import React from 'react';
import { IonInputOtp } from '@ionic/react';
function Example() {
return (
<>
<IonInputOtp size="small"> Small </IonInputOtp>
<IonInputOtp size="medium"> Medium </IonInputOtp>
<IonInputOtp size="large"> Large </IonInputOtp>
</>
);
}
export default Example;
Vue
<template>
<ion-input-otp size="small"> Small </ion-input-otp>
<ion-input-otp size="medium"> Medium </ion-input-otp>
<ion-input-otp size="large"> Large </ion-input-otp>
</template>
<script setup lang="ts">
import { IonInputOtp } from '@ionic/vue';
</script>
구분선 (Separators)
separators 속성은 하나 이상의 입력 상자 사이에 시각적 구분선을 추가합니다. 구분선은 세 가지 방식으로 정의할 수 있습니다:
- 쉼표로 구분된 숫자 문자열 (예:
"1,3") - 숫자 배열 (예:
[1, 3]) - 모든 입력 상자 사이에 구분선을 표시하는 문자열
"all"숫자는 구분선이 표시되어야 하는 인덱스 이후를 의미합니다. 예를 들어"1,3"은 첫 번째와 세 번째 입력 상자 뒤에 구분선을 표시합니다. 이를 이용해 입력 상자들을 시각적으로 구분되는 그룹으로 만들 수 있지만, 값은 여전히 하나로 유지됩니다.
JavaScript
<ion-input-otp separators="1,3"> Didn't get a code? <a href="#">Resend the code</a> </ion-input-otp>
<ion-input-otp separators="2"> Didn't get a code? <a href="#">Resend the code</a> </ion-input-otp>
<ion-input-otp separators="all"> Didn't get a code? <a href="#">Resend the code</a> </ion-input-otp>
Angular
src/app/example.component.html
<ion-input-otp separators="1,3"> Didn't get a code? <a href="#">Resend the code</a> </ion-input-otp>
<ion-input-otp separators="2"> Didn't get a code? <a href="#">Resend the code</a> </ion-input-otp>
<ion-input-otp separators="all"> Didn't get a code? <a href="#">Resend the code</a> </ion-input-otp>
src/app/example.component.ts
import { Component } from '@angular/core';
import { IonInputOtp } from '@ionic/angular';
@Component({
selector: 'app-example',
templateUrl: 'example.component.html',
styleUrls: ['example.component.css'],
imports: [IonInputOtp],
})
export class ExampleComponent {}
React
import React from 'react';
import { IonInputOtp } from '@ionic/react';
function Example() {
return (
<>
<IonInputOtp separators="1,3">
Didn't get a code? <a href="#">Resend the code</a>
</IonInputOtp>
<IonInputOtp separators="2">
Didn't get a code? <a href="#">Resend the code</a>
</IonInputOtp>
<IonInputOtp separators="all">
Didn't get a code? <a href="#">Resend the code</a>
</IonInputOtp>
</>
);
}
export default Example;
Vue
<template>
<ion-input-otp separators="1,3"> Didn't get a code? <a href="#">Resend the code</a> </ion-input-otp>
<ion-input-otp separators="2"> Didn't get a code? <a href="#">Resend the code</a> </ion-input-otp>
<ion-input-otp separators="all"> Didn't get a code? <a href="#">Resend the code</a> </ion-input-otp>
</template>
<script setup lang="ts">
import { IonInputOtp } from '@ionic/vue';
</script>
상태 (States)
이 컴포넌트는 입력 상자에 대한 자동 스타일링을 위해 다양한 상태를 지원합니다:
- 각각의 속성을 통한
disabled및readonly상태 - 폼 유효성 검사 상태: CSS 클래스를 통해 시각적으로 표시되는
valid및invalid - Angular에서는: 프레임워크의 value accessor와 폼 유효성 검사를 통해 유효성 검사 상태가 자동으로 관리됩니다
- 다른 프레임워크에서는: 개발자가
ion-valid,ion-invalid,ion-touched클래스를 수동으로 추가해야 합니다 ion-invalid스타일은 touched(ion-touched)일 때만 표시됩니다ion-valid스타일은 focused(has-focus)일 때만 표시됩니다 JavaScript
<ion-input-otp disabled value="1234"> Disabled </ion-input-otp>
<ion-input-otp readonly value="1234"> Readonly </ion-input-otp>
<ion-input-otp value="12"></ion-input-otp>
<ion-input-otp value="1234" class="has-focus"></ion-input-otp>
<script>
customElements.whenDefined('ion-input-otp').then(() => {
const otpInputs = document.querySelectorAll('ion-input-otp:not([disabled]):not([readonly])');
otpInputs.forEach((input) => {
// Mark as touched on initialization
input.classList.add('ion-touched');
// Validate on initialization
validateOtp(input);
// Add input event listener for real-time validation
input.addEventListener('ionInput', (event) => validateOtp(event.target));
});
});
function validateOtp(input) {
const value = input.value;
// Remove existing validation classes
input.classList.remove('ion-valid');
input.classList.remove('ion-invalid');
// Input is valid if value is exactly 4 digits
if (value && value.toString().length === 4) {
input.classList.add('ion-valid');
input.textContent = 'Valid';
} else {
input.classList.add('ion-invalid');
input.textContent = 'Invalid';
}
}
</script>
Angular
src/app/example.component.html
<ion-input-otp disabled value="1234"> Disabled </ion-input-otp>
<ion-input-otp readonly value="1234"> Readonly </ion-input-otp>
<form [formGroup]="myForm">
<ion-input-otp formControlName="first">{{ getValidationText('first') }}</ion-input-otp>
<ion-input-otp formControlName="second" class="has-focus">{{ getValidationText('second') }}</ion-input-otp>
</form>
src/app/example.component.ts
import { Component, OnInit } from '@angular/core';
import {
FormBuilder,
FormGroup,
FormsModule,
ReactiveFormsModule,
Validators,
AbstractControl,
ValidationErrors,
} from '@angular/forms';
import { IonInputOtp } from '@ionic/angular';
function otpRequiredLength(length: number) {
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
if (!value || value.toString().length !== length) {
return { otpLength: true };
}
return null;
};
}
@Component({
selector: 'app-example',
templateUrl: 'example.component.html',
styleUrls: ['example.component.css'],
imports: [IonInputOtp, ReactiveFormsModule, FormsModule],
})
export class ExampleComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
first: [12, [Validators.required, otpRequiredLength(4)]],
second: [1234, [Validators.required, otpRequiredLength(4)]],
});
}
ngOnInit() {
this.markFormGroupTouched(this.myForm);
}
markFormGroupTouched(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach((key) => {
const control = formGroup.get(key);
if (control) {
control.markAsTouched();
}
});
}
getValidationText(controlName: string): string {
const control = this.myForm.get(controlName);
if (!control) return '';
if (control.valid && control.value) {
return 'Valid';
} else if (control.invalid && control.touched) {
return 'Invalid';
}
return '';
}
}
React
import React, { useState } from 'react';
import { IonInputOtp } from '@ionic/react';
function Example() {
const [inputs, setInputs] = useState([{ value: '12' }, { value: '1234' }]);
const getValidationState = (value: string) => ({
class: value.length === 4 ? 'ion-valid' : 'ion-invalid',
text: value.length === 4 ? 'Valid' : 'Invalid',
});
const handleInput = (index: number, value: string) => {
setInputs((prev) => prev.map((input, i) => (i === index ? { ...input, value } : input)));
};
return (
<>
<IonInputOtp disabled value="1234">
Disabled
</IonInputOtp>
<IonInputOtp readonly value="1234">
Readonly
</IonInputOtp>
{inputs.map((input, index) => (
<IonInputOtp
key={index}
value={input.value}
onIonInput={(e) => handleInput(index, e.detail.value!)}
className={`ion-touched ${index === 1 ? 'has-focus' : ''} ${getValidationState(input.value).class}`}
>
<span>{getValidationState(input.value).text}</span>
</IonInputOtp>
))}
</>
);
}
export default Example;
Vue
<template>
<ion-input-otp disabled value="1234"> Disabled </ion-input-otp>
<ion-input-otp readonly value="1234"> Readonly </ion-input-otp>
<ion-input-otp
v-for="(input, index) in inputs"
:key="index"
:value="input.value"
class="ion-touched has-focus"
:class="[getInputClasses(input.value)]"
@ionInput="(e) => input.value = e.target.value"
>
<span>{{ getValidationMessage(input.value) }}</span>
</ion-input-otp>
</template>
<script setup lang="ts">
import { IonInputOtp } from '@ionic/vue';
import { ref } from 'vue';
const inputs = ref([{ value: '12' }, { value: '1234' }]);
const getInputClasses = (value: string) => ({
'ion-valid': value.length === 4,
'ion-invalid': value.length < 4,
});
const getValidationMessage = (value: string) => (value.length === 4 ? 'Valid' : 'Invalid');
</script>
패턴 (Pattern)
pattern 속성은 정규 표현식(regular expression)을 사용한 사용자 정의 검증을 지원합니다. 허용되는 문자를 검증하기 위해 문자열 정규 표현식 또는 유니코드 정규 표현식을 받습니다. pattern은 부분 집합이 아닌 전체 값과 일치해야 합니다. 기본 패턴:
type="number": 어떤 문자 체계(script)의 어떤 숫자 문자와도 일치하는"[\p{N}]"type="text": 어떤 문자 체계의 숫자 문자와 어떤 언어의 문자도 모두 허용하는"[\p{L}\p{N}]"컴포넌트는 지정된 패턴과 일치하지 않는 문자를 사용자가 입력하지 못하도록 막습니다. 개발자는 특정 입력 요구사항에 맞추기 위해 자신만의 pattern 문자열을 제공하여 이 기본값을 재정의(override)할 수 있습니다.
팁 (Tip)
사용자 정의 pattern을 사용할 때는 type 속성이 모바일 기기에서 어떤 키보드가 나타나는지를 제어한다는 점을 기억하세요:
- 숫자 전용 패턴에는 숫자 키보드를 표시하도록
type="number"를 사용하세요 - 문자를 포함하는 패턴에는 영숫자 키보드를 표시하도록
type="text"를 사용하세요
JavaScript
<ion-input-otp pattern="[1-4]" value="123"> Numbers 1-4 only </ion-input-otp>
<ion-input-otp type="text" pattern="." value="!@#"> All characters allowed </ion-input-otp>
<ion-input-otp type="text" pattern="[A-Z]" autocapitalize="on" value="ABC"> Capital Latin letters only </ion-input-otp>
<ion-input-otp type="text" pattern="[\p{Script=Greek}]" value="αβγ"> Greek characters only </ion-input-otp>
<ion-input-otp type="text" pattern="[\p{Script=Arabic}]" value="ابت"> Arabic characters only </ion-input-otp>
<ion-input-otp type="text" pattern="[\p{Script=Han}]" value="甲乙丙"> Chinese characters only </ion-input-otp>
Angular
src/app/example.component.html
<ion-input-otp pattern="[1-4]" value="123"> Numbers 1-4 only </ion-input-otp>
<ion-input-otp type="text" pattern="." value="!@#"> All characters allowed </ion-input-otp>
<ion-input-otp type="text" pattern="[A-Z]" autocapitalize="on" value="ABC"> Capital Latin letters only </ion-input-otp>
<ion-input-otp type="text" pattern="[\p{Script=Greek}]" value="αβγ"> Greek characters only </ion-input-otp>
<ion-input-otp type="text" pattern="[\p{Script=Arabic}]" value="ابت"> Arabic characters only </ion-input-otp>
<ion-input-otp type="text" pattern="[\p{Script=Han}]" value="甲乙丙"> Chinese characters only </ion-input-otp>
src/app/example.component.ts
import { Component } from '@angular/core';
import { IonInputOtp } from '@ionic/angular';
@Component({
selector: 'app-example',
templateUrl: 'example.component.html',
styleUrls: ['example.component.css'],
imports: [IonInputOtp],
})
export class ExampleComponent {}
React
import React from 'react';
import { IonInputOtp } from '@ionic/react';
function Example() {
return (
<>
<IonInputOtp pattern="[1-4]" value="123">
Numbers 1-4 only
</IonInputOtp>
<IonInputOtp type="text" pattern="." value="!@#">
All characters allowed
</IonInputOtp>
<IonInputOtp type="text" pattern="[A-Z]" autocapitalize="on" value="ABC">
Capital Latin letters only
</IonInputOtp>
<IonInputOtp type="text" pattern="[\p{Script=Greek}]" value="αβγ">
Greek characters only
</IonInputOtp>
<IonInputOtp type="text" pattern="[\p{Script=Arabic}]" value="ابت">
Arabic characters only
</IonInputOtp>
<IonInputOtp type="text" pattern="[\p{Script=Han}]" value="甲乙丙">
Chinese characters only
</IonInputOtp>
</>
);
}
export default Example;
Vue
<template>
<ion-input-otp pattern="[1-4]" value="123"> Numbers 1-4 only </ion-input-otp>
<ion-input-otp type="text" pattern="." value="!@#"> All characters allowed </ion-input-otp>
<ion-input-otp type="text" pattern="[A-Z]" autocapitalize="on" value="ABC">
Capital Latin letters only
</ion-input-otp>
<ion-input-otp type="text" pattern="[\p{Script=Greek}]" value="αβγ"> Greek characters only </ion-input-otp>
<ion-input-otp type="text" pattern="[\p{Script=Arabic}]" value="ابت"> Arabic characters only </ion-input-otp>
<ion-input-otp type="text" pattern="[\p{Script=Han}]" value="甲乙丙"> Chinese characters only </ion-input-otp>
</template>
<script setup lang="ts">
import { IonInputOtp } from '@ionic/vue';
</script>
테마 적용 (Theming)
색상 (Colors)
color 속성은 입력 상자의 색상 팔레트를 변경합니다. outline 채우기의 경우 이 속성은 캐럿(caret) 색상, 하이라이트 색상, 테두리 색상을 변경합니다. solid 채우기의 경우 이 속성은 캐럿 색상과 하이라이트 색상을 변경합니다.
참고 (Note)
color 속성은 input OTP의 텍스트 색상을 변경하지 않습니다. 텍스트 색상을 바꾸려면 --color CSS property를 사용하세요.
JavaScript
<ion-input-otp length="2" color="primary"> Primary </ion-input-otp>
<ion-input-otp length="2" color="secondary"> Secondary </ion-input-otp>
<ion-input-otp length="2" color="tertiary"> Tertiary </ion-input-otp>
<ion-input-otp length="2" color="success"> Success </ion-input-otp>
<ion-input-otp length="2" color="warning"> Warning </ion-input-otp>
<ion-input-otp length="2" color="danger"> Danger </ion-input-otp>
<ion-input-otp length="2" color="light"> Light </ion-input-otp>
<ion-input-otp length="2" color="medium"> Medium </ion-input-otp>
<ion-input-otp length="2" color="dark"> Dark </ion-input-otp>
Angular
src/app/example.component.html
<ion-input-otp length="2" color="primary"> Primary </ion-input-otp>
<ion-input-otp length="2" color="secondary"> Secondary </ion-input-otp>
<ion-input-otp length="2" color="tertiary"> Tertiary </ion-input-otp>
<ion-input-otp length="2" color="success"> Success </ion-input-otp>
<ion-input-otp length="2" color="warning"> Warning </ion-input-otp>
<ion-input-otp length="2" color="danger"> Danger </ion-input-otp>
<ion-input-otp length="2" color="light"> Light </ion-input-otp>
<ion-input-otp length="2" color="medium"> Medium </ion-input-otp>
<ion-input-otp length="2" color="dark"> Dark </ion-input-otp>
src/app/example.component.ts
import { Component } from '@angular/core';
import { IonInputOtp } from '@ionic/angular';
@Component({
selector: 'app-example',
templateUrl: 'example.component.html',
styleUrls: ['example.component.css'],
imports: [IonInputOtp],
})
export class ExampleComponent {}
React
import React from 'react';
import { IonInputOtp } from '@ionic/react';
function Example() {
return (
<>
<IonInputOtp length={2} color="primary">Primary</IonInputOtp>
<IonInputOtp length={2} color="secondary">Secondary</IonInputOtp>
<IonInputOtp length={2} color="tertiary">Tertiary</IonInputOtp>
<IonInputOtp length={2} color="success">Success</IonInputOtp>
<IonInputOtp length={2} color="warning">>Warning</IonInputOtp>
<IonInputOtp length={2} color="danger">Danger</IonInputOtp>
<IonInputOtp length={2} color="light">Light</IonInputOtp>
<IonInputOtp length={2} color="medium">Medium</IonInputOtp>
<IonInputOtp length={2} color="dark">Dark</IonInputOtp>
</>
);
}
export default Example;
Vue
<template>
<ion-input-otp length="2" color="primary"> Primary </ion-input-otp>
<ion-input-otp length="2" color="secondary"> Secondary </ion-input-otp>
<ion-input-otp length="2" color="tertiary"> Tertiary </ion-input-otp>
<ion-input-otp length="2" color="success"> Success </ion-input-otp>
<ion-input-otp length="2" color="warning"> Warning </ion-input-otp>
<ion-input-otp length="2" color="danger"> Danger </ion-input-otp>
<ion-input-otp length="2" color="light"> Light </ion-input-otp>
<ion-input-otp length="2" color="medium"> Medium </ion-input-otp>
<ion-input-otp length="2" color="dark"> Dark </ion-input-otp>
</template>
<script setup lang="ts">
import { IonInputOtp } from '@ionic/vue';
</script>
CSS 사용자 정의 속성 (CSS Custom Properties)
Input OTP는 scoped 캡슐화(encapsulation)를 사용합니다. 즉 런타임에 각 스타일에 추가 클래스를 붙여 CSS를 자동으로 스코프(scope) 처리한다는 뜻입니다. scoped 셀렉터를 재정의하려면 더 높은 특이성(specificity)을 가진 셀렉터가 필요합니다. ion-input-otp 자체를 대상으로 커스터마이즈하는 것은 동작하지 않으므로, 클래스를 추가해서 그 방식으로 커스터마이즈하는 것을 권장합니다. 일부 스타일은 fill에 따라 적용되기 때문에, 각 fill에 대해 속성을 개별적으로 재정의해야 할 수도 있습니다.
JavaScript
<ion-input-otp class="custom" separators="all"> Didn't get a code? <a href="#">Resend the code</a> </ion-input-otp>
<ion-input-otp fill="solid" class="custom" separators="all">
Didn't get a code? <a href="#">Resend the code</a>
</ion-input-otp>
<style>
ion-input-otp.custom {
--separator-color: rgb(90, 23, 237, 0.12);
--highlight-color-focused: #5a17ed;
}
.input-otp-fill-outline.custom {
--border-color: rgb(90, 23, 237, 0.6);
--color: #5a17ed;
}
.input-otp-fill-solid.custom {
--border-color: rgb(90, 23, 237, 0.12);
--background: rgb(90, 23, 237, 0.12);
}
</style>
Angular
src/app/example.component.html
<ion-input-otp class="custom" separators="all"> Didn't get a code? <a href="#">Resend the code</a> </ion-input-otp>
<ion-input-otp fill="solid" class="custom" separators="all">
Didn't get a code? <a href="#">Resend the code</a>
</ion-input-otp>
src/app/example.component.css
ion-input-otp.custom {
--separator-color: rgb(90, 23, 237, 0.12);
--highlight-color-focused: #5a17ed;
}
.input-otp-fill-outline.custom {
--border-color: rgb(90, 23, 237, 0.6);
--color: #5a17ed;
}
.input-otp-fill-solid.custom {
--border-color: rgb(90, 23, 237, 0.12);
--background: rgb(90, 23, 237, 0.12);
}
src/app/example.component.ts
import { Component } from '@angular/core';
import { IonInputOtp } from '@ionic/angular';
@Component({
selector: 'app-example',
templateUrl: 'example.component.html',
styleUrls: ['example.component.css'],
imports: [IonInputOtp],
})
export class ExampleComponent {}
React
src/main.tsx
import React from 'react';
import { IonInputOtp } from '@ionic/react';
import './main.css';
function Example() {
return (
<>
<IonInputOtp class="custom" separators="all">
Didn't get a code? <a href="#">Resend the code</a>
</IonInputOtp>
<IonInputOtp fill="solid" class="custom" separators="all">
Didn't get a code? <a href="#">Resend the code</a>
</IonInputOtp>
</>
);
}
export default Example;
src/main.css
ion-input-otp.custom {
--separator-color: rgb(90, 23, 237, 0.12);
--highlight-color-focused: #5a17ed;
}
.input-otp-fill-outline.custom {
--border-color: rgb(90, 23, 237, 0.6);
--color: #5a17ed;
}
.input-otp-fill-solid.custom {
--border-color: rgb(90, 23, 237, 0.12);
--background: rgb(90, 23, 237, 0.12);
}
Vue
<template>
<ion-input-otp class="custom" separators="all"> Didn't get a code? <a href="#">Resend the code</a> </ion-input-otp>
<ion-input-otp fill="solid" class="custom" separators="all">
Didn't get a code? <a href="#">Resend the code</a>
</ion-input-otp>
</template>
<script setup lang="ts">
import { IonInputOtp } from '@ionic/vue';
</script>
<style>
ion-input-otp.custom {
--separator-color: rgb(90, 23, 237, 0.12);
--highlight-color-focused: #5a17ed;
}
.input-otp-fill-outline.custom {
--border-color: rgb(90, 23, 237, 0.6);
--color: #5a17ed;
}
.input-otp-fill-solid.custom {
--border-color: rgb(90, 23, 237, 0.12);
--background: rgb(90, 23, 237, 0.12);
}
</style>
접근성 (Accessibility)
키보드 상호작용 (Keyboard Interactions)
Input OTP의 키보드 탐색은 ARIA Authoring Practices Guide의 복합 위젯(composite widget) 권장 사항을 따릅니다. 단일 컨트롤로 동작하는 여러 개의 포커스 가능한 요소(입력 상자들)를 포함하기 때문에 복합 위젯으로 취급됩니다.
이 키보드 상호작용은 컴포넌트가 비활성화되지 않은 모든 ion-input-otp 요소에 적용됩니다.
| Key | Description |
|---|---|
| Tab | 컴포넌트에 처음 탭으로 진입하면 첫 번째 빈 상자로 포커스가 이동합니다. 모든 상자가 채워져 있으면 마지막 상자로 이동합니다. 컴포넌트 안에 들어온 뒤에는 탭이 페이지의 다음 포커스 가능한 요소로 이동합니다. |
| Shift + Tab | 컴포넌트에 역방향으로 탭으로 진입하면 첫 번째 빈 상자로 포커스가 이동합니다. 모든 상자가 채워져 있으면 마지막 상자로 이동합니다. 컴포넌트 안에 들어온 뒤에는 시프트 탭 포커스가 페이지의 이전 포커스 가능한 요소로 이동합니다. |
| ArrowRight | 다음 입력 상자로 포커스를 이동하며, 첫 번째 빈 상자에서 멈춥니다. RTL 모드에서는 값이 들어 있는 이전 상자로 포커스를 다시 이동합니다. |
| ArrowLeft | 값이 들어 있는 이전 상자로 포커스를 다시 이동합니다. RTL 모드에서는 다음 입력 상자로 포커스를 이동하며, 첫 번째 빈 상자에서 멈춥니다. |
pattern 속성과 일치하는 아무 문자 |
현재 상자를 채우고 자동으로 다음 빈 상자로 포커스를 이동합니다. 모든 상자가 채워져 있으면 포커스는 마지막 상자에 유지됩니다. 현재 상자에 값이 있으면 입력한 문자로 해당 값을 덮어씁니다. RTL 모드에서는 입력이 오른쪽에서 왼쪽으로 상자를 채웁니다. |
| Backspace | 빈 상자에서: 한 상자 뒤로 포커스를 이동하고 값을 지웁니다. 값이 있는 상자에서: 해당 값을 지웁니다. 오른쪽 상자들에 값이 있을 때: 모두 한 위치 왼쪽으로 이동시킵니다. RTL 모드에서 왼쪽 상자들에 값이 있을 때: 모두 한 위치 오른쪽으로 이동시킵니다. |
| Ctrl + V Cmd + V | 현재 어느 상자에 포커스가 있는지와 관계없이 첫 번째 상자부터 콘텐츠를 붙여넣습니다. 붙여넣기 전에 모든 기존 값을 지웁니다. 예를 들어 모든 상자에 "1234"가 있고 "56"을 붙여넣으면, 결과는 처음 두 상자에 "56"이 들어가고 나머지 상자는 비어 있습니다. 붙여넣은 콘텐츠가 사용 가능한 상자 수보다 길면 초과 문자는 무시됩니다. |
Properties (속성)
autocapitalize
설명 (Description): 사용자가 입력/편집할 때 텍스트 값을 자동으로 대문자화할지, 어떻게 할지를 나타냅니다. 사용 가능한 옵션: "off", "none", "on", "sentences", "words", "characters".
Attribute: autocapitalize
Type: string
Default: 'off'
color
설명 (Description): 애플리케이션의 색상 팔레트에서 사용할 색상입니다. 기본 옵션은 "primary", "secondary", "tertiary", "success", "warning", "danger", "light", "medium", "dark"입니다. 색상에 대한 더 자세한 내용은 theming을 참고하세요.
Attribute: color
Type: "danger" | "dark" | "light" | "medium" | "primary" | "secondary" | "success" | "tertiary" | "warning" | string | undefined
Default: undefined
disabled
설명 (Description): true이면 사용자가 입력과 상호작용할 수 없습니다.
Attribute: disabled
Type: boolean
Default: false
fill
설명 (Description): 입력 상자의 채우기(fill)입니다. "solid"이면 입력 상자에 배경이 생기고, "outline"이면 입력 상자가 테두리와 함께 투명해집니다.
Attribute: fill
Type: "outline" | "solid" | undefined
Default: 'outline'
inputmode
설명 (Description): 브라우저에 어떤 키보드를 표시할지 알려주는 힌트입니다. 가능한 값: "none", "text", "tel", "url", "email", "numeric", "decimal", "search". 숫자의 경우(type="number"): "numeric" 텍스트의 경우(type="text"): "text"
Attribute: inputmode
Type: "decimal" | "email" | "none" | "numeric" | "search" | "tel" | "text" | "url" | undefined
Default: undefined
length
설명 (Description): 표시할 입력 상자의 개수입니다.
Attribute: length
Type: number
Default: 4
pattern
설명 (Description): 허용되는 문자의 정규 표현식 패턴 문자열입니다. type에 따라 기본값이 달라집니다. 숫자의 경우 (type="number" ): "[\p{N}]" 텍스트의 경우 (type="text" ): "[\p{L}\p{N}]"
Attribute: pattern
Type: string | undefined
Default: undefined
readonly
설명 (Description): true이면 사용자가 값을 수정할 수 없습니다.
Attribute: readonly
Type: boolean
Default: false
separators
설명 (Description): 입력 상자 사이에 구분선을 표시할 위치입니다. 쉼표로 구분된 문자열 또는 숫자 배열이 될 수 있습니다. 예: "3"은 3번째 입력 상자 뒤에 구분선을 표시합니다. [1,4]는 1번째와 4번째 입력 상자 뒤에 구분선을 표시합니다. "all"은 모든 입력 상자 사이에 구분선을 표시합니다.
Attribute: separators
Type: number[] | string | undefined
Default: undefined
shape
설명 (Description): 입력 상자의 모양입니다. "round"이면 테두리 반경이 커집니다. "rectangular"이면 테두리 반경이 없습니다. "soft"이면 부드러운 테두리 반경을 갖습니다.
Attribute: shape
Type: "rectangular" | "round" | "soft"
Default: 'round'
size
설명 (Description): 입력 상자의 크기입니다.
Attribute: size
Type: "large" | "medium" | "small"
Default: 'medium'
type
설명 (Description): 입력 상자에서 허용되는 입력 타입입니다.
Attribute: type
Type: "number" | "text"
Default: 'number'
value
설명 (Description): 입력 그룹의 값입니다.
Attribute: value
Type: null | number | string | undefined
Default: ''
Events (이벤트)
| Name | Description | Bubbles |
|---|---|---|
ionBlur |
입력 그룹이 포커스를 잃었을 때 발생합니다. | true |
ionChange |
ionChange 이벤트는 사용자가 입력의 값을 수정할 때 발생합니다. ionInput 이벤트와 달리, ionChange 이벤트는 사용자가 입력하는 동안이 아니라 변경 사항이 커밋(commit)되었을 때만 발생합니다. ionChange 이벤트는 값이 변경된 후 <ion-input-otp> 컴포넌트가 포커스를 잃을 때 발생합니다. 이 이벤트는 value 속성을 프로그래밍 방식으로 설정할 때는 발생하지 않습니다. |
true |
ionComplete |
모든 입력 상자가 유효한 값으로 채워졌을 때 발생합니다. | true |
ionFocus |
입력 그룹이 포커스를 가졌을 때 발생합니다. | true |
ionInput |
ionInput 이벤트는 사용자가 입력의 값을 수정할 때마다 발생합니다. ionChange 이벤트와 달리, ionInput 이벤트는 입력 값의 각 변경마다 발생합니다. 일반적으로 사용자가 타이핑할 때 키 입력마다 발생합니다. 텍스트 입력(type=text, type=tel 등)을 받는 요소의 인터페이스는 InputEvent이고, 그 외에는 Event입니다. 편집 시 입력이 지워지면 타입은 null입니다. |
true |
Methods (메서드)
setFocus
설명 (Description): 입력 상자에 포커스를 설정합니다.
Signature: setFocus(index?: number) => Promise<void>
매개변수 (Parameters): index: - 포커스할 입력 상자의 인덱스(0부터 시작)입니다. 제공되고 해당 입력 상자에 값이 있으면 그 인덱스의 입력 상자에 포커스가 갑니다. 그렇지 않으면 첫 번째 빈 입력 상자에, 모두 채워져 있다면 마지막 입력에 포커스가 갑니다.
CSS Shadow Parts
이 컴포넌트에서 사용할 수 있는 CSS shadow part는 없습니다.
CSS Custom Properties
iOS
| Name | Description |
|---|---|
--background |
입력 상자의 배경색 |
--border-color |
입력 상자의 테두리 색상 |
--border-radius |
입력 상자의 테두리 반경 |
--border-width |
입력 상자의 테두리 두께 |
--color |
입력의 텍스트 색상 |
--height |
입력 상자의 높이 |
--highlight-color-focused |
포커스되었을 때 입력에 표시되는 하이라이트 색상 |
--highlight-color-invalid |
유효하지 않을 때 입력에 표시되는 하이라이트 색상 |
--highlight-color-valid |
유효할 때 입력에 표시되는 하이라이트 색상 |
--margin-bottom |
입력 그룹의 아래쪽 여백 |
--margin-end |
방향이 왼쪽에서 오른쪽이면 오른쪽 여백, 오른쪽에서 왼쪽이면 왼쪽 여백 |
--margin-start |
방향이 왼쪽에서 오른쪽이면 왼쪽 여백, 오른쪽에서 왼쪽이면 오른쪽 여백 |
--margin-top |
입력 그룹의 위쪽 여백 |
--min-width |
입력 상자의 최소 너비 |
--padding-bottom |
입력 그룹의 아래쪽 패딩 |
--padding-end |
방향이 왼쪽에서 오른쪽이면 오른쪽 패딩, 오른쪽에서 왼쪽이면 왼쪽 패딩 |
--padding-start |
방향이 왼쪽에서 오른쪽이면 왼쪽 패딩, 오른쪽에서 왼쪽이면 오른쪽 패딩 |
--padding-top |
입력 그룹의 위쪽 패딩 |
--separator-border-radius |
상자 사이 구분선의 테두리 반경 |
--separator-color |
상자 사이 구분선의 색상 |
--separator-height |
상자 사이 구분선의 높이 |
--separator-width |
상자 사이 구분선의 너비 |
--width |
입력 상자의 너비 |
MD
| Name | Description |
|---|---|
--background |
입력 상자의 배경색 |
--border-color |
입력 상자의 테두리 색상 |
--border-radius |
입력 상자의 테두리 반경 |
--border-width |
입력 상자의 테두리 두께 |
--color |
입력의 텍스트 색상 |
--height |
입력 상자의 높이 |
--highlight-color-focused |
포커스되었을 때 입력에 표시되는 하이라이트 색상 |
--highlight-color-invalid |
유효하지 않을 때 입력에 표시되는 하이라이트 색상 |
--highlight-color-valid |
유효할 때 입력에 표시되는 하이라이트 색상 |
--margin-bottom |
입력 그룹의 아래쪽 여백 |
--margin-end |
방향이 왼쪽에서 오른쪽이면 오른쪽 여백, 오른쪽에서 왼쪽이면 왼쪽 여백 |
--margin-start |
방향이 왼쪽에서 오른쪽이면 왼쪽 여백, 오른쪽에서 왼쪽이면 오른쪽 여백 |
--margin-top |
입력 그룹의 위쪽 여백 |
--min-width |
입력 상자의 최소 너비 |
--padding-bottom |
입력 그룹의 아래쪽 패딩 |
--padding-end |
방향이 왼쪽에서 오른쪽이면 오른쪽 패딩, 오른쪽에서 왼쪽이면 왼쪽 패딩 |
--padding-start |
방향이 왼쪽에서 오른쪽이면 왼쪽 패딩, 오른쪽에서 왼쪽이면 오른쪽 패딩 |
--padding-top |
입력 그룹의 위쪽 패딩 |
--separator-border-radius |
상자 사이 구분선의 테두리 반경 |
--separator-color |
상자 사이 구분선의 색상 |
--separator-height |
상자 사이 구분선의 높이 |
--separator-width |
상자 사이 구분선의 너비 |
--width |
입력 상자의 너비 |
Slots
| Name | Description |
|---|---|
| 기본 슬롯(default slot)입니다 |
더 알아보기 (Learn more)
ion-input-otp는 length, type, shape, fill, size, separators, pattern 등 다양한 속성으로 입력 상자의 개수·형식·모양·검증을 조절할 수 있어요. 폼 상태에 따라 ion-valid/ion-invalid 클래스로 스타일링되며, 키보드 접근성과 RTL 지원까지 고려된 컴포넌트랍니다.