搜尋套件、儲存庫與 APP 分類

套件詳情v2.1.1

form_validator

Flutter 表單欄位小部件最簡單的表單驗證庫

AndroidiOSWebmacOSWindowsLinux
近 30 天下載
1.3萬
喜歡數
240
Pub 分數
160

安裝套件

flutter pub add form_validator

套件介紹

根據套件公開資料產生的選型評估,僅供參考。

form_validator 是一個輕量且直覺的套件,用於在 Flutter 應用程式中驗證表單欄位。它提供了一個簡單的 API 來定義驗證規則,例如必填欄位、電子郵件格式、長度限制以及自訂驗證器。專為 Flutter 的 FormField 小工具設計,它簡化了確保使用者輸入符合指定標準的過程,無需撰寫重複程式碼。該函式庫可與現有表單無縫整合,並支援多個平台,包括 Android、iOS、Web、macOS、Windows 和 Linux。

適用情境

  • 驗證使用者註冊表單
  • 檢查電子郵件和密碼輸入
  • 確保欄位長度要求
  • 實現自定義驗證邏輯
  • 簡化表單狀態管理

主要特色

  • 最小化設定和配置
  • 支援必要、電子郵件、長度和自訂驗證器
  • 與 Flutter 內建的 FormField 小工具搭配使用
  • 跨平台相容性
  • 驗證失敗時顯示明確的錯誤訊息

適合對象

  • 初階到中階 Flutter 開發者
  • 需要基本到中等表單驗證的應用程式
  • 優先考慮程式碼乾淨、易讀的驗證

使用建議

  • 僅限基本驗證場景
  • 無內建國際化支援
  • 不處理複雜的嵌套表單結構

原始 README

以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。

form_validator

pub package GitHub GitHub Workflow Status codecov

Simplest form validation for flutter form widgets.

  • Zero dependency
  • Localization supported
  • Extensible
  • Well tested
  • Open source

Example

TextFormField(
  validator: ValidationBuilder().email().maxLength(50).build(),
  decoration: InputDecoration(labelText: 'Email'),
),

live demo

Getting Started

Installation

Add form_validator as dependency to your flutter project by adding this lines to pubspec.yaml.

dependencies:
  form_validator: ">=0.1.1 <2.0.0"

Then run flutter pub get to install required dependencies.

Check installation tab for more information

Code

Import form_validator package to your dart widgets by writing:

import 'package:form_validator/form_validator.dart';

Now you can use ValidationBuilder class to create validation logic. Here's simple validator that validates if input length is between 10 and 50 characters long.

final validate = ValidationBuilder().minLength(10).maxLength(50).build();

print(validate('test'));        // Minimum length must be at least 10 characters
print(validate('Hello World')); // null, means value is correct

Localization

You can set global locale using ValidationBuilder.setLocale(String localeName) or you can also define locale on ValidationBuilder({ String localeName }) constructor.

ValidationBuilder.setLocale('en');

// will use *en* localization
ValidationBuilder()
  .minLength(5)
  .build();

// will use *az* localization
ValidationBuilder(localeName: 'az')
  .minLength(5)
  .build();

// will display custom message
ValidationBuilder()
  .minLength(5, 'Length < 5 😟')
  .build();

Methods

.minLength(int minLength, [String message])

Validates if value length is not less than minLength.

.maxLength(int maxLength, [String message])

Validates if value length is not more than maxLength.

.email([String message])

Checks if value is an email address.

.phone([String message])

Checks if value is an phone number.

Note: This method might be changed in future.

.ip([String message])

Checks if value is correct IPv4 address.

.ipv6([String message])

Checks if value is correct IPv6 address.

.url([String message])

Checks if value is correct url address.

.match(String otherValue, [String message])

Checks if the value matches the specified otherValue. This can be used to validate if two input values are identical.

.regExp(RegExp regExp, String message)

Validates if value does matches regExp or not.

message argument is required in this method.

.or(Action<ValidationBuilder> left, Action<ValidationBuilder> right, {bool reverse = false})

Validates if value passes any of left and right validations. If value doesn't passes any error message from right validation will be displayed (If reverse set to true message from left validation will be displayed).

Example:

print(
  ValidationBuilder().or(
    (builder) => builder.email('not email'),
    (builder) => builder.phone('not phone'),
  )
  .test('invalid')
); // not phone

print(
  ValidationBuilder().or(
    (builder) => builder.email('not email'),
    (builder) => builder.phone('not phone'),
    reverse: true,
  )
  .test('invalid')
); // not email

Notes

ValidationBuilder is mutable.

You need to construct different instances for each validation.

Wrong
final builder = ValidationBuilder().email();

TextFormField(
  validator: builder.maxLength(50).build(),
),
TextFormField(
  validator: builder.maxLength(20).build(),
),
Correct
final validator1 = ValidationBuilder().email().maxLength(50).build();
final validator2 = ValidationBuilder().email().maxLength(20).build();

TextFormField(
  validator: validator1,
),
TextFormField(
  validator: validator2,
),
Add custom localization

Firstly you need to extend abstract FormValidatorLocale class.

import 'package:form_validator/form_validator.dart';

class MyValidationLocale extends FormValidatorLocale {
  @override
  String name() => "custom";

  @override
  String required() => "Field is required";

  ...
}

PROTIP: You can copy a language file from /lib/src/i18n folder and modify messages as you want.

Then you can use your custom locale class as global or local validation locale.

// global locale
void main() {
  ValidationBuilder.globalLocale = MyValidationLocale();
  ...
}

// local locale
final locale = MyValidationLocale();

build(BuildContext context) {
  final emailValidator = ValidationBuilder(locale: locale)
    .email()
    .build();
  ...
}

PROTIP: Feel free to add your locale to library by opening pull request TheMisir/form-validator to support library.

Extending ValidationBuilder

You can use dart extension methods to extend ValidationBuilder.

extension CustomValidationBuilder on ValidationBuilder {
  password() => add((value) {
    if (value == 'password') {
      return 'Password should not "password"';
    }
    return null;
  });
}

final validator = ValidationBuilder().password().build();

Support

If you would like to support this library you could translate messages to your own language.

所屬分類

原始碼儲存庫

使用此套件的專案