Flutter表单验证插件master_validator的使用
Flutter表单验证插件master_validator的使用
Live Demo
文档
简单的Flutter表单验证库。
- 容易上手
- 轻量级
- 可自定义错误信息
- 验证器链式调用
获取新文档
文档
入门指南
安装
在项目根目录运行以下命令,将master_validator
添加为依赖项:
flutter pub add master_validator
然后运行flutter pub get
来安装所需的依赖项。
导入
在Dart小部件中导入master_validator
包:
import 'package:master_validator/master_validator.dart';
这使得Validators
类在你的代码空间中可用。
基本必填字段验证
使用Validators.Required()
使字段成为必填字段:
TextFormField(
validator: Validators.Required(
errorMessage: "此字段不能为空",
)
),
邮箱验证
使用Validators.Email()
进行邮箱验证:
TextFormField(
validator: Validators.Required(
next : Validators.Email(),
),
),
内置验证方法
Validators.Required()
Validators.Email()
Validators.Number()
(可选参数:integerOnly
、allowNegative
、allowDecimal
)Validators.LengthBetween()
Validators.Minlength()
Validators.Maxlength()
Validators.Url()
Validators.Regex()
Validators.Equals()
Validators.FileName()
Validators.DirectoryName()
每个验证器都有一个errorMessage
参数用于自定义错误信息,并且有一个next
参数用于链式调用另一个验证器。
使用多个验证器(链式调用验证器)
所有验证器都接受一个next
参数,你可以指定另一个验证器(自定义函数或预定义验证器):
TextFormField(
validator: Validators.Required(
next : Validators.Email(
next : Validators.Maxlength(50)
),
),
),
注意: 链式调用时顺序很重要!
注意: 默认情况下,除了Validators.Required()
之外的所有验证器都不会在数据为空或null时抛出错误。这意味着如果你定义了一个验证器如:
TextFormField(
validator: Validators.Email(),
),
这意味着该字段是一个可选字段,但如果输入了数据,则必须符合电子邮件格式。要改变这种行为并使其成为必填字段,请使用Validators.Required()
作为第一个验证器,例如:
TextFormField(
validator: Validators.Required(
next : Validators.Url(),
),
),
有关详细用法,请查看 示例代码。
示例代码
import 'package:flutter/material.dart';
import 'package:master_validator/master_validator.dart';
import 'package:master_validator_example/widgets/primary_button.dart';
import 'widgets/input.dart';
import 'widgets/space.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
[@override](/user/override)
void initState() {
super.initState();
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primaryColor: const Color(0xff262626),
appBarTheme: const AppBarTheme(
centerTitle: true,
color: Color(0xff262626),
elevation: 0,
titleTextStyle: TextStyle(
color: Colors.white,
),
iconTheme: IconThemeData(
color: Colors.white,
),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xff262b40),
foregroundColor: const Color(0xff181b28),
),
),
useMaterial3: true,
),
debugShowCheckedModeBanner: false,
home: const FormValidationExample(),
);
}
}
enum SnackbarMessageType { Success, Error }
class FormValidationExample extends StatefulWidget {
const FormValidationExample({super.key});
[@override](/user/override)
State<FormValidationExample> createState() => _FormValidationExampleState();
}
class _FormValidationExampleState extends State<FormValidationExample> {
final _formKey = GlobalKey<FormState>();
void showSnackbar(String message, SnackbarMessageType type) {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message, style: const TextStyle(color: Colors.white)),
backgroundColor:
type == SnackbarMessageType.Success ? Colors.green : Colors.red,
),
);
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Master Validator Example'),
),
body: ListView(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
children: [
const Space(20),
const Text("Validators.Email (Required)"),
Space.def,
Form(
autovalidateMode: AutovalidateMode.onUserInteraction,
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Input(
validator: Validators.Required(next: Validators.Email()),
prefixIcon: Icons.alternate_email_rounded,
hintText: "Email",
),
const Space(20),
const Text("Validators.Number (Optional)"),
Space.def,
Input(
validator: Validators.Number(),
prefixIcon: Icons.numbers,
hintText: "Phone Number",
),
const Space(20),
const Text(
"Validators.Minlength + Validators.Maxlength (Required)"),
Space.def,
Input(
validator: Validators.Required(
errorMessage: "Username cannot be empty",
next: Validators.MinLength(
errorMessage: "Username must be at least 3 characters",
length: 3,
next: Validators.MaxLength(
length: 8,
errorMessage: "Username must be at most 8 characters",
),
),
),
prefixIcon: Icons.person,
hintText: "Username",
),
const Space(20),
const Text("Validators.LengthBetween"),
Space.def,
Input(
validator: Validators.LengthBetween(3, 10),
prefixIcon: Icons.key,
hintText: "Password",
),
const Space(20),
const Text("Validators.URL (Optional)"),
Space.def,
Input(
validator: Validators.Url(),
prefixIcon: Icons.link,
hintText: "URL",
),
const Space(20),
const Text("Validators.Regex (Optional)"),
Space.def,
Input(
validator: Validators.Regex(
pattern: r'^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$',
errorMessage: "Invalid Hex Color Code",
),
prefixIcon: Icons.link,
hintText: "Hex Color Code ex - #000000",
),
const Space(20),
const Text("Validators.Equals (Optional)"),
Space.def,
Input(
validator: Validators.Equals(
value: '123456',
errorMessage:
"Password matches with previous password, enter a new password",
),
prefixIcon: Icons.key,
hintText: "New Password (123456)",
),
const Space(20),
const Text("Validators.FileName (Optional)"),
Space.def,
Input(
validator: Validators.FileName(),
prefixIcon: Icons.file_present,
hintText: "File Name",
),
const Space(20),
const Text("Validators.FileSize"),
Space.def,
Input(
validator: Validators.DirectoryName(),
prefixIcon: Icons.folder,
hintText: "Directory Name (Optional)",
),
],
),
),
Space.def,
PrimaryButton(
label: "Validate",
onclick: () {
// 验证表单
if (_formKey.currentState!.validate()) {
showSnackbar("表单有效", SnackbarMessageType.Success);
} else {
showSnackbar("表单无效", SnackbarMessageType.Error);
}
},
),
],
),
);
}
}
更多关于Flutter表单验证插件master_validator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter表单验证插件master_validator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何使用 master_validator
插件来进行 Flutter 表单验证的代码示例。master_validator
是一个用于 Flutter 的表单验证库,它简化了表单字段验证的过程。
首先,确保你已经在 pubspec.yaml
文件中添加了 master_validator
依赖:
dependencies:
flutter:
sdk: flutter
master_validator: ^最新版本号 # 请替换为最新的版本号
然后,运行 flutter pub get
来安装依赖。
接下来是一个完整的示例,展示了如何使用 master_validator
进行表单验证:
import 'package:flutter/material.dart';
import 'package:master_validator/master_validator.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final formKey = GlobalKey<FormState>();
final _validator = MasterValidator([
ValidatorItem(
field: 'email',
rules: [
RequiredRule(),
EmailRule(),
],
),
ValidatorItem(
field: 'password',
rules: [
RequiredRule(),
MinLengthRule(6),
],
),
ValidatorItem(
field: 'confirmPassword',
rules: [
RequiredRule(),
MustMatchRule('password'),
],
),
]);
String? email;
String? password;
String? confirmPassword;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Form Validation with master_validator'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: formKey,
child: Column(
children: [
TextFormField(
decoration: InputDecoration(labelText: 'Email'),
validator: (value) {
final result = _validator.validateField('email', value);
return result?.message ?? null;
},
onSaved: (value) => email = value,
),
TextFormField(
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
validator: (value) {
final result = _validator.validateField('password', value);
return result?.message ?? null;
},
onSaved: (value) => password = value,
),
TextFormField(
decoration: InputDecoration(labelText: 'Confirm Password'),
obscureText: true,
validator: (value) {
final result = _validator.validateField('confirmPassword', value);
return result?.message ?? null;
},
onSaved: (value) => confirmPassword = value,
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
if (formKey.currentState!.validate()) {
final results = await _validator.validateAll();
if (results.isEmpty) {
formKey.currentState!.save();
// Handle successful form submission
print('Email: $email');
print('Password: $password');
} else {
// Show validation errors
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Please fix the errors in the form.'),
),
);
}
}
},
child: Text('Submit'),
),
],
),
),
),
);
}
}
在这个示例中,我们创建了一个简单的表单,包含三个字段:Email、Password 和 Confirm Password。我们使用了 MasterValidator
来定义每个字段的验证规则。在提交表单时,我们首先调用 formKey.currentState!.validate()
来验证 Flutter 自带的验证规则(如果有的话),然后调用 _validator.validateAll()
来执行 master_validator
定义的验证规则。
注意:
ValidatorItem
用于定义每个字段的验证规则。RequiredRule
表示字段是必填的。EmailRule
表示字段必须是有效的电子邮件地址。MinLengthRule(6)
表示字段的最小长度为6个字符。MustMatchRule('password')
表示字段的值必须与名为 ‘password’ 的字段匹配。
如果所有验证都通过,则保存表单数据并执行相应的操作(如打印到控制台)。否则,显示一个包含验证错误的 SnackBar。