패키지, 저장소 및 앱 카테고리 검색

form_model 표지
패키지 상세v1.0.2+2

form_model

Flutter 애플리케이션을 위한 강력하고 유연한 폼 검증 패키지입니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
11
좋아요
8
Pub 점수
160

패키지 설치

flutter pub add form_model

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

form_model은 폼 생성, 검증 및 상태 관리를 단순화하기 위해 설계된 강력한 Flutter 패키지입니다. 실시간 검증, 자동 포맷팅 및 마스킹을 내장한 유연한 프레임워크를 제공하여 동적 폼을 쉽게 구축할 수 있습니다. 개발자는 폼 필드를 쉽게 정의하고, 유효성 검사기를 적용하며, 최소한의 반복 코드로 변경에 반응할 수 있습니다. 이 패키지는 모든 주요 플랫폼과 원활하게 통합되어 일관된 폼 동작이 필요한 크로스플랫폼 애플리케이션에 이상적입니다.

사용 사례

  • 동적 폼 생성
  • 실시간 입력 검증
  • 사용자 입력 자동 형식 지정
  • 크로스 플랫폼 양식 일관성
  • 복잡한 폼 상태 관리

주요 기능

  • 내장된 검증 규칙
  • 자동 형식 지정 및 마스킹
  • 반응형 폼 상태 업데이트
  • 확장 가능한 필드 유형
  • 최소한의 보일러플레이트 설정

적합한 대상

  • 복잡한 폼을 구축하는 개발자
  • 엄격한 입력 검증이 필요한 앱
  • 크로스 플랫폼 Flutter 프로젝트
  • 유지보수 가능한 폼 코드를 우선시하는 팀

고려 사항

  • 반응형 프로그래밍에 대한 이해가 필요합니다
  • 고급 기능에 대한 학습 곡선
  • 인기 있는 대안들에 비해 문서가 제한적

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

form_model

A powerful and flexible form validation package for Flutter applications.

flutter platform pub package BSD-2-Clause

Features

  • 🚀 Easy-to-use form validation
  • 🎯 Single-responsibility validators for clear, maintainable code
  • 🌐 Built-in internationalization support with fallback locales
  • 🧩 Extensible with custom validators and translations
  • 🔄 Immutable state management
  • 🔗 Integrates seamlessly with Flutter widgets
  • 🎛️ Advanced form controls (date pickers, multi-select, etc.)
  • 🧬 Works great with state management solutions like BLoC
  • 🧪 Comprehensive test coverage

Screenshots

Here are some screenshots of form_model in action:

Screenshot 1 Screenshot 2 Screenshot 3 Screenshot 4 Screenshot 5 Screenshot 6 Screenshot 7

Installation

Add form_model to your pubspec.yaml file:

dependencies:
  form_model: ^1.0.2+2

Then run:

flutter pub get

Basic Usage

Here's a simple example of how to use form_model:

import 'package:form_model/form_model.dart';

// Create a FormModel for an email field
final emailModel = FormModel<String>(
  validators: [RequiredValidator(), EmailValidator()],
);

// Set a value and validate
final validatedModel = emailModel.setValue('user@example.com').validate();

if (validatedModel.isValid) {
  print('Email is valid: ${validatedModel.value}');
} else {
  print('Validation error: ${validatedModel.error?.translatedMessage}');
}

Note: Each validator is responsible for checking one specific aspect of the input and returns only one type of error. This principle should be followed when creating custom validators for your application.

Advanced Usage

For more complex forms, you can combine multiple FormModel instances. Here's an example with a password confirmation field:

class RegistrationForm {
  final FormModel<String> username;
  final FormModel<String> email;
  final FormModel<String> password;
  late final FormModel<String> confirmPassword;

  RegistrationForm({
    required this.username,
    required this.email,
    required this.password,
  }) {
    confirmPassword = FormModel<String>(
      validators: [
        RequiredValidator(),
        StringConfirmPasswordMatchValidator(matchingValue: password.value),
      ],
    );
  }

  bool get isValid => 
    username.isValid && 
    email.isValid && 
    password.isValid && 
    confirmPassword.isValid;

  void validate() {
    username.validate();
    email.validate();
    password.validate();
    confirmPassword = confirmPassword
      .replaceValidator(
        predicate: (validator) => validator is StringConfirmPasswordMatchValidator,
        newValidator: StringConfirmPasswordMatchValidator(matchingValue: password.value),
      )
      .validate();
  }

  void updatePassword(String newPassword) {
    password.setValue(newPassword);
    // Update confirm password validator
    confirmPassword = confirmPassword
      .replaceValidator(
        predicate: (validator) => validator is StringConfirmPasswordMatchValidator,
        newValidator: StringConfirmPasswordMatchValidator(matchingValue: newPassword),
      );
  }
}

This example demonstrates how to properly set up and update a password match validator.

Validators

form_model includes a wide range of built-in validators, each responsible for a single aspect of validation:

  • RequiredValidator
  • EmailValidator
  • StringMinLengthValidator
  • StringMaxLengthValidator
  • PasswordLengthValidator
  • PasswordUppercaseValidator
  • PasswordLowercaseValidator
  • PasswordNumberValidator
  • PasswordSpecialCharValidator
  • DateTimeValidator
  • StringDateTimeAgeMinValidator
  • StringDateTimeAgeMaxValidator
  • StringPhoneNumberValidator
  • StringNumbersOnlyValidator
  • StringTextOnlyValidator
  • StringUrlValidator
  • StringWordsCountMinValidator
  • StringWordsCountMaxValidator
  • StringCreditCardValidator
  • CustomEqualValidator
  • StringCustomPatternValidator
  • IpAddressValidator
  • Ipv6AddressValidator
  • StringNumMinValidator
  • StringNumMaxValidator
  • StringContainsValidator
  • StringNotContainsValidator
  • FileTypeValidator
  • FileSizeValidator
  • BoolTrueValidator
  • BoolFalseValidator
  • BoolAgreeToTermsAndConditionsValidator

Each validator focuses on a single validation rule, adhering to the single-responsibility principle.

Internationalization

form_model supports multiple languages out of the box:

// Set the current locale
FormModelLocalizations().setCurrentLocale(const Locale('es'));

// Get a translated error message
final errorMessage = emailModel.error?.translatedMessage;
Supported Languages

form_model supports the following languages:

  • English (en)
  • Spanish (es)
  • French (fr)
  • German (de)
  • Arabic (ar)
  • Chinese (Simplified) (zh_CN)
  • Hindi (hi)
  • Italian (it)
  • Japanese (ja)
  • Korean (ko)
  • Dutch (nl)
  • Portuguese (pt)
  • Russian (ru)
  • Turkish (tr)
  • Ukrainian (uk)
  • Vietnamese (vi)
  • Polish (pl)
  • Swedish (sv)

Integration with BLoC and Freezed

form_model integrates seamlessly with the BLoC pattern. Here's an example of a Flutter BLoC state using Freezed:

@freezed
class RegistrationState with _$RegistrationState {
  const factory RegistrationState({
    @Default(FormModel<String>(validators: [RequiredValidator()]))
    FormModel<String> username,
    
    @Default(FormModel<String>(validators: [RequiredValidator(), EmailValidator()]))
    FormModel<String> email,
    
    @Default(FormModel<String>(validators: [
      RequiredValidator(),
      PasswordLengthValidator(minLength: 8),
      PasswordUppercaseValidator(),
      PasswordLowercaseValidator(),
      PasswordNumberValidator(),
      PasswordSpecialCharValidator(),
    ]))
    FormModel<String> password,
    
    @Default(false) bool isSubmitting,
    @Default(false) bool isSuccess,
    String? errorMessage,
  }) = _RegistrationState;
}

Custom Validators

Custom validators allow you to create specific validation rules not covered by built-in validators. Here's a simple example of a custom validator that checks if a string starts with a specific prefix:

String? validatePrefix(String? value) {
  const requiredPrefix = 'USER_';
  if (value == null || !value.startsWith(requiredPrefix)) {
    return 'Value must start with $requiredPrefix';
  }
  return null;
}

final userIdModel = FormModel<String>(
  validators: [
    RequiredValidator(),
    CustomValidator(validator: validatePrefix),
  ],
);

// Usage
void validateUserId(String userId) {
  final validatedModel = userIdModel.setValue(userId).validate();
  if (validatedModel.isValid) {
    print('Valid User ID: ${validatedModel.value}');
  } else {
    print('Invalid User ID: ${validatedModel.error?.translatedMessage}');
  }
}

// Example
validateUserId('USER_123'); // Valid
validateUserId('ADMIN_456'); // Invalid

This custom validator checks if the input string starts with the prefix 'USER_'. It demonstrates how you can easily create application-specific validation logic using custom validators.

Custom validation functions should return a string with an error message if validation fails, or null if it passes. This approach allows you to extend form_model's capabilities to suit your specific needs while maintaining clean and modular code.

Working with Custom Objects

form_model can handle complex custom objects as well. Here's an example using an Address class:

class Address {
  final String street;
  final String city;

  Address({required this.street, required this.city});
}

String? validateStreet(Address? value) {
  if (value == null || value.street.isEmpty) return 'Street is required';
  return null;
}

String? validateCity(Address? value) {
  if (value == null || value.city.isEmpty) return 'City is required';
  return null;
}

final addressModel = FormModel<Address>(
  validators: [
    CustomValidator(validator: validateStreet),
    CustomValidator(validator: validateCity),
  ],
);

// Usage
void updateAddress(String street, String city) {
  final newAddress = Address(street: street, city: city);
  addressModel.setValue(newAddress).validate();
}

This approach allows you to validate complex objects while keeping individual validation rules separate and focused.

Custom Translations

You can set custom translations for both custom and predefined error messages:

void setCustomTranslations() {
  // Set custom translation for a custom error
  FormModelLocalizations().setCustomErrorTranslations(
    'en',
    const CustomFormErrorKey('password_no_exclamation'),
    'Password must contain an exclamation mark',
  );

  // Override translation for a predefined error
  FormModelLocalizations().setCustomErrorTranslations(
    'en',
    const PredefinedFormErrorKey(PredefinedFormErrorType.required),
    'This field cannot be left empty',
  );

  // Set translations for other languages
  FormModelLocalizations().setCustomErrorTranslations(
    'es',
    const CustomFormErrorKey('password_no_exclamation'),
    'La contraseña debe contener un signo de exclamación',
  );

  FormModelLocalizations().setCustomErrorTranslations(
    'es',
    const PredefinedFormErrorKey(PredefinedFormErrorType.required),
    'Este campo no puede estar vacío',
  );
}

Call this function early in your app's lifecycle to set up custom translations.

Contributing

Contributions are welcome! Please read our contributing guidelines to get started. The package already has comprehensive test coverage, but additional tests for new features are always appreciated.

License

This project is licensed under the 3-Clause BSD License - see the LICENSE file for details.

카테고리

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.