Form | CoUI

Form

폼 유효성 검증 컴포넌트

Form#

여러 입력 필드를 묶어 유효성 검증을 수행하는 폼 컴포넌트입니다.

Live Preview#

Web
Flutter
Loading Flutter...
class FormDefaultExample extends StatelessComponent {
  const FormDefaultExample({super.key});

  @override
  Component build(BuildContext context) {
    return Form(
      children: [
        FormField(
          label: 'Username',
          child: TextField(
            placeholder: Component.text('Username'),
            onChanged: (_) {},
          ),
        ),
        FormField(
          label: 'Email',
          child: TextField(
            placeholder: Component.text('Email'),
            onChanged: (_) {},
          ),
        ),
        Button(
          variant: CoreButtonVariant.primary,
          onPressed: () {},
          child: Component.text('Submit'),
        ),
      ],
    );
  }
}
class FormDefaultExample extends StatelessWidget {
  const FormDefaultExample({super.key});

  @override
  Widget build(BuildContext context) {
    return Form(
      children: [
        FormField(
          label: 'Username',
          child: TextField(placeholder: const Text('Username')),
        ),
        FormField(
          label: 'Email',
          child: TextField(placeholder: const Text('Email')),
        ),
        Button(
          variant: CoreButtonVariant.primary,
          onPressed: () {},
          child: const Text('Submit'),
        ),
      ],
    );
  }
}

사용 시기 (When to Use)#

이 컴포넌트를 사용하세요:

  • 여러 입력 필드의 유효성 검증을 한꺼번에 관리할 때
  • 제출 전 사용자 입력을 검증하고 에러 피드백을 제공할 때
  • 필드 간 상호 의존적인 검증이 필요할 때 (비밀번호 확인 등)

대신 다른 컴포넌트를 사용하세요:

  • TextField: 단일 입력 필드만 필요하고 폼 검증이 불필요할 때
  • Dialog: 간단한 확인 입력은 다이얼로그 내에서 직접 처리할 때

기본 사용법 (Basic Usage)#

Form(
  children: [
    FormField(
      label: '이름',
      required: true,
      child: TextField(placeholder: Text('홍길동')),
    ),
    FormField(
      label: '이메일',
      child: TextField(placeholder: Text('example@email.com')),
    ),
    Button(
      variant: CoreButtonVariant.primary,
      onPressed: handleSubmit,
      child: Text('제출'),
    ),
  ],
)
Form(
  onSubmit: handleSubmit,
  children: [
    FormField(
      label: '이름',
      required: true,
      child: TextField(placeholder: text('홍길동')),
    ),
    FormField(
      label: '이메일',
      child: TextField(placeholder: text('example@email.com')),
    ),
    Button(
      variant: CoreButtonVariant.primary,
      onPressed: handleSubmit,
      child: text('제출'),
    ),
  ],
)

Props / Parameters#

Form#

속성타입기본값설명
children List<Widget>? / List<Component>? null 폼 내용
onSubmit VoidCallback? null 폼 제출 콜백
rowSpacing double? CoreSpace.space24 (24.0) 필드 간 간격
controller FormController? null 폼 상태 컨트롤러 (Flutter·Web 공통)

FormField#

속성타입기본값설명
labelString?null필드 라벨 텍스트
labelWidget Widget? / Component? null 커스텀 라벨 위젯
child Widget? / Component? null 입력 위젯
error String? null 수동 에러 메시지 (컨트롤러 검증 결과가 우선)
description String? null 도움말 텍스트
requiredboolfalse필수 입력 표시
enabledbooltrue활성화 여부
validator Validator<dynamic>? null 자식 입력값 검증기 (Flutter·Web 공통)
formKey FormKey<dynamic>? null (자동 생성) 컨트롤러 내 필드 식별자
formFieldStyle CoreFormFieldStyle? null chrome / gap 슬롯 스타일 (labelInputGapStyle 등)

변형 (Variants)#

에러 상태#

FormField(
  label: '이메일',
  error: '올바른 이메일을 입력하세요',
  required: true,
  child: TextField(placeholder: Text('이메일')),
)

설명 텍스트#

FormField(
  label: '비밀번호',
  description: '8자 이상, 대소문자 및 숫자를 포함하세요',
  child: TextField(placeholder: Text('비밀번호')),
)

비활성화#

FormField(
  label: '이름',
  enabled: false,
  child: TextField(placeholder: Text('수정 불가')),
)

동작 스펙 (Behavior)#

controlled-state 는 Flutter·Web 공통입니다. FormController / FormKey / Validator / FormValidationMode 계약과 검증 알고리즘이 coui_core 단일소스에 있고, 두 플랫폼이 같은 API 로 동작합니다 (메커니즘만 다름 — Flutter ChangeNotifier, Web listener bag).

유효성 검증 모드 (FormValidationMode)#

모드설명
initial필드 생성 시 즉시 검증
changed사용자가 값을 변경할 때 검증
submitted폼 제출 시 검증

controlled form (Flutter·Web 공통)#

Form(controller:) 안에서 FormField(validator:) 를 쓰면, 자식 입력(Checkbox / Toggle / RadioGroup 등)이 값을 자동 보고하고 검증 결과가 필드에 표시됩니다. caller 가 필드별로 배선할 필요가 없습니다.

final controller = FormController();

Form(
  controller: controller,
  children: [
    FormField(
      label: '약관 동의',
      required: true,
      formKey: agreeKey,
      validator: const RequiredValidator<CoreCheckboxState>(),
      child: Checkbox(state: agreed, onChanged: setAgreed),
    ),
  ],
)

// 값 접근 / 에러 확인 (양 플랫폼 동일)
final agreed = controller.getValue(agreeKey);
final allValues = controller.values;
final errors = controller.errors;
final agreeError = controller.getSyncError(agreeKey);

// 재검증 — 플랫폼별 검증 컨텍스트로 트리거
//   Flutter: controller.revalidate(CoUIValidationContext(context), .submitted)
//   Web:     controller.revalidate(CoUIWebValidationContext(), .submitted)

Validator 시스템 (Flutter·Web 공통)#

검증기는 coui_core 에 정의되어 양 플랫폼이 공유합니다. 연산자로 조합합니다.

// AND: 모든 조건 충족 (& / + / combine)
final validator = const RequiredValidator<String>() & customValidator;

// OR: 하나 이상 충족
final validator = aValidator | bValidator;

// NOT: 조건 반전 (생성자로 — `~` 연산자는 없습니다)
final validator = NotValidator(customValidator);

내장 검증기: RequiredValidator<T> (필수 — null/빈 문자열 거부), NotValidator<T> (반전), OrValidator<T> (OR), CompositeValidator<T> (AND). 커스텀 검증은 Validator<T> 를 상속해 validate(CoreValidationContext, value, mode) 를 구현합니다.

사용 가이드라인 (Usage Guidelines)#

✅ Do#

필수 필드를 명확히 표시하세요.

FormField(
  label: '이름',
  required: true,
  child: TextField(placeholder: Text('홍길동')),
)

어떤 필드가 필수인지 미리 알려주면 제출 실패를 줄일 수 있습니다.


❌ Don't#

필수/선택 구분 없이 필드를 나열하지 마세요.

FormField(
  label: '이름',
  // required 표시 없음
  child: TextField(placeholder: Text('이름')),
)

사용자가 어떤 필드를 채워야 하는지 알 수 없어 제출 실패가 반복됩니다.

✅ Do#

에러 메시지에 수정 방법을 안내하세요.

FormField(
  label: '비밀번호',
  error: '8자 이상, 대소문자 및 숫자를 포함하세요',
  child: TextField(placeholder: Text('비밀번호')),
)

구체적인 기준을 알려주면 사용자가 즉시 수정할 수 있습니다.


❌ Don't#

모호한 에러 메시지를 사용하지 마세요.

FormField(
  label: '비밀번호',
  error: '유효하지 않은 비밀번호',
  child: TextField(placeholder: Text('비밀번호')),
)

무엇이 틀렸는지 알 수 없으면 여러 번 시도해야 합니다.

접근성 (Accessibility)#

키보드 인터랙션#

동작
Tab다음 폼 필드로 이동
Shift+Tab이전 폼 필드로 이동
Enter폼 제출 (단일 라인 입력 필드에서)

스크린 리더#

  • Flutter: FormFieldlabel이 입력 필드와 자동 연결. 에러 발생 시 에러 메시지가 실시간으로 읽힘
  • Web: <label> 요소의 네이티브 접근성 자동 처리

크로스 플랫폼 차이점 (Platform Differences)#

controlled-state 의 capability·API 는 양 플랫폼 동일합니다 (계약·검증 로직이 coui_core 단일소스). 차이는 메커니즘(런타임) 뿐입니다.

항목FlutterWeb
클래스명 Form + FormField Form + FormField
상태 관리 FormController (capability 동일) FormController (capability 동일)
컨트롤러 메커니즘 ChangeNotifier + post-frame notify listener bag + microtask notify
컨트롤러 공유 Data.inherit FormControllerScope (InheritedComponent)
유효성 검증 Validator<T> 시스템 (공유) Validator<T> 시스템 (공유)
크로스 필드 검증shouldRevalidateshouldRevalidate
검증기 조합 연산자 (&, ` , +) + NotValidator`
검증 컨텍스트 CoUIValidationContext(context) CoUIWebValidationContext()
  • TextField: 텍스트 입력 필드. FormField로 감싸 라벨/에러 표시
  • Select: 드롭다운 선택. 폼 필드로 사용 가능
  • Checkbox: 체크박스 입력. 약관 동의 등에 활용
  • Button: 폼 제출 버튼

조합 예제#

// 회원가입 폼 패턴
Form(
  children: [
    FormField(
      label: '이름',
      required: true,
      child: TextField(placeholder: Text('홍길동')),
    ),
    FormField(
      label: '이메일',
      required: true,
      child: TextField(placeholder: Text('example@email.com')),
    ),
    FormField(
      label: '비밀번호',
      required: true,
      description: '8자 이상, 대소문자 및 숫자를 포함하세요',
      child: TextField(placeholder: Text('비밀번호')),
    ),
    Button(
      variant: CoreButtonVariant.primary,
      onPressed: handleSignUp,
      child: Text('가입하기'),
    ),
  ],
)