Flutter表单验证插件flutter_validation的使用
Flutter表单验证插件flutter_validation的使用
描述
这个插件为Flutter应用程序中的表单字段提供了一组常用的验证函数。
示例
以下是插件提供的几种常见验证示例:
验证类型 | 示例图片 |
---|---|
Required | |
Strong Password | |
Combined Required and Email | |
Phone | |
Maximum Length 16 | |
Combined Email and Phone |
主要功能
- 必填字段验证:检查字段是否为空。
- 电子邮件验证:基于正则表达式验证电子邮件地址。
- 电话号码验证:基本电话号码验证(可扩展)。
- 字母数字验证:仅允许字母和数字。
- 密码强度验证:检查大写、小写字母、数字和特殊字符(可自定义)。
- 最小和最大长度验证:强制字段的最小和最大字符长度。
- 组合电话/电子邮件验证:允许用户输入有效的电话号码或电子邮件地址。
- 组合多个验证器:组合多个验证器进行复杂验证。
安装
在pubspec.yaml
文件中添加以下依赖:
dependencies:
flutter_validations: ^0.0.2
可用的验证器
requiredValidator
:检查字段是否为空。emailValidator
:验证电子邮件地址。phoneValidator
:基本电话号码验证(可扩展)。alphanumericValidator
:仅允许字母和数字。upperCaseValidator
:检查密码中是否包含大写字母。lowerCaseValidator
:检查密码中是否包含小写字母。digitValidator
:检查密码中是否包含数字。specialCharValidator
:检查密码中是否包含特殊字符。maxLengthValidator
:强制最大字符长度。minLengthValidator
:强制最小字符长度。combinedPhoneEmailValidator
:允许电话号码或电子邮件。combineValidators
:组合多个验证器。
使用方法
使用Flutter_validation
使用Validators
类及其函数,例如:
必填验证器
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: firstNameController,
validator: (value) =>
Validators().requiredValidator(
errorMessage: '此字段不能为空',
value: value
),
),
电子邮件验证器
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: emailController,
validator: (value) =>
Validators().emailValidator(
errorMessage: '请输入有效的电子邮件地址',
value: value
),
),
组合验证器
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: usernameController,
validator: (value) =>
Validators().combineValidators(
validators: [
Validators().requiredValidator(errorMessage: '用户名不能为空', value: value),
Validators().minLengthValidator(minLength: 3, errorMessage: '请输入至少3个字符的用户名', value: value),
Validators().upperCaseValidator(errorMessage: '用户名必须包含至少1个大写字母', value: value),
]
),
),
字母数字验证器
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: alphanumericController,
validator: (value) =>
Validators().alphanumericValidator(value: value),
// 这将返回“请输入仅包含字母和数字”的验证错误
),
完整示例代码
以下是一个完整的示例代码,展示了如何使用flutter_validation
插件进行表单验证:
import 'package:flutter/material.dart';
import 'package:flutter_validation/flutter_validation.dart';
import 'package:flutter_validation/src/validate.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({
super.key,
});
[@override](/user/override)
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final formKey = GlobalKey<FormState>();
final TextEditingController emailController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
final TextEditingController confirmPassController = TextEditingController();
final TextEditingController strongPasswordController = TextEditingController();
final TextEditingController combineController = TextEditingController();
final TextEditingController phoneController = TextEditingController();
final TextEditingController maxlenController = TextEditingController();
final TextEditingController minlenController = TextEditingController();
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
),
body: Center(
child: Form(
key: formKey,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 25, vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('电子邮件'),
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: emailController,
validator: (value) =>
Validate().emailValidator(
errorMessage: '请输入有效的电子邮件地址',
value: value
),
),
const SizedBox(height: 20),
const Text('必填'),
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: passwordController,
validator: (value) =>
Validators().requiredValidator(
errorMessage: '此字段不能为空',
value: value
),
),
const SizedBox(height: 20),
const Text('强密码'),
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: confirmPassController,
validator: (value) =>
Validators().strongPassWordValidation(validations: [
Validators().upperCaseValidator(value: value),
Validators().lowerCaseValidator(value: value),
Validators().digitValidator(value: value),
// Validators().specialCharValidator(value: value),
], value: value),
),
const SizedBox(height: 20),
const Text('带特殊字符的强密码'),
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: strongPasswordController,
validator: (value) =>
Validators().strongPassWordValidation(
errorMessage: '密码必须包含数字',
value: value
),
),
const SizedBox(height: 20),
const Text('组合必填和电子邮件'),
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: combineController,
validator: (value) =>
Validators().combineValidators(validators: [
Validators().requiredValidator(value: value),
Validators().emailValidator(value: value),
Validators().strongPassWordValidation(value: value),
]),
),
const SizedBox(height: 20),
const Text('电话号码'),
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: phoneController,
validator: (value) =>
Validators().phoneValidator(value: value),
),
const SizedBox(height: 20),
const Text('最大长度 (16)'),
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: maxlenController,
validator: (value) =>
Validators().maxLengthValidator(value: value, maxLength: 16),
),
const SizedBox(height: 20),
const Text('组合电子邮件和电话号码'),
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: minlenController,
validator: (value) =>
Validators().combinedPhoneEmailValidator(value: value),
),
],
),
),
),
),
);
}
}
更多关于Flutter表单验证插件flutter_validation的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter表单验证插件flutter_validation的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter中使用flutter_validation
插件来进行表单验证的示例代码。
首先,确保你已经在pubspec.yaml
文件中添加了flutter_validation
依赖:
dependencies:
flutter:
sdk: flutter
flutter_validation: ^x.y.z # 请替换为最新版本号
然后,运行flutter pub get
来安装依赖。
接下来是一个完整的示例,展示如何使用flutter_validation
进行表单验证:
import 'package:flutter/material.dart';
import 'package:flutter_validation/flutter_validation.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Validation Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final TextEditingController _nameController = TextEditingController();
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final FormValidator _formValidator = FormValidator()
..addValidators([
FieldValidator<String>.of('name', [_nameController.text])
.isRequired()
.isLengthMin(4),
FieldValidator<String>.of('email', [_emailController.text])
.isRequired()
.isEmail(),
FieldValidator<String>.of('password', [_passwordController.text])
.isRequired()
.isLengthMin(6)
]);
void _submitForm() {
if (_formKey.currentState!.validate()) {
_formValidator.validate().then((result) {
if (result.isAllValid) {
// 所有字段都有效,执行提交操作
print('Form Submitted Successfully');
// 例如,可以将数据发送到服务器
} else {
// 处理验证错误
result.errorFields!.forEach((field, messages) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("${field.toUpperCase()}: ${messages.join(', ')}"),
),
);
});
}
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Validation Example'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: _nameController,
decoration: InputDecoration(labelText: 'Name'),
validator: (value) {
if (value == null || value.isEmpty || value.length < 4) {
return 'Name must be at least 4 characters long';
}
return null;
},
),
TextFormField(
controller: _emailController,
decoration: InputDecoration(labelText: 'Email'),
validator: (value) {
if (value == null || value.isEmpty || !value.contains('@')) {
return 'Please enter a valid email address';
}
return null;
},
),
TextFormField(
controller: _passwordController,
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
validator: (value) {
if (value == null || value.isEmpty || value.length < 6) {
return 'Password must be at least 6 characters long';
}
return null;
},
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _submitForm,
child: Text('Submit'),
),
],
),
),
),
);
}
@override
void dispose() {
_nameController.dispose();
_emailController.dispose();
_passwordController.dispose();
super.dispose();
}
}
在这个示例中,我们展示了如何使用flutter_validation
插件进行表单验证。不过,请注意,虽然flutter_validation
插件可以简化验证过程,但上面的示例中我们仍然保留了Flutter自带的validator
属性来演示基本的表单验证。
对于flutter_validation
插件的使用,我们在_submitForm
方法中调用了_formValidator.validate()
方法,它会根据我们之前定义的验证规则对表单字段进行验证,并返回一个包含验证结果的Future
对象。如果所有字段都有效,我们可以执行提交操作;如果有字段无效,我们可以显示相应的错误信息。
注意:由于flutter_validation
插件的API可能会随着版本更新而变化,因此建议查阅最新的官方文档以获取最准确的信息。如果你发现上述代码无法正常运行,可能是因为插件的API已经发生了更改。