Flutter数据验证插件generic_validator的使用
Flutter数据验证插件generic_validator的使用
此插件提供了API,以帮助将验证和业务规则从应用程序的展示层分离出来。
特性
- 使用声明式方式表达你的规则。
- 反馈不必为特定类型(完全通用)。
- 将相关的规则分组在一起,并消除if else语句。
- 支持异步规则评估。
使用方法
检查示例以获取详细用法
检查/example
文件夹以获取完整的示例用法。
final myName = 'Ahmed';
final arabicName = 'احمد';
final nameRule = ValidationRule(
ruler: (value) {
if (RegExp("[A-Za-z]").hasMatch(value)) {
return true;
}
return false;
},
negativeFeedback: "Name has to be in English");
final validResult = nameRule.apply(myName); // 返回有效
final invalidResult = nameRule.apply(arabicName); // 返回无效,其原因属性为之前传递的负反馈类型。
将规则分组在一起
将规则分组在一起可以使操作更方便。你可以继承Validator
类并重写其rules
获取器来声明你的规则。
class NameValidator extends Validator<String, dynamic> {
[@override](/user/override)
List<ValidationRule<String, dynamic>> get rules => [
ValidationRule(
ruler: (value) {
if (value.isNotEmpty) {
return true;
}
return false;
},
negativeFeedback: "Name can't be empty"),
ValidationRule(
ruler: (value) {
if (RegExp("[A-Za-z]").hasMatch(value)) {
return true;
}
return false;
},
negativeFeedback: "Name has to be in English"),
];
}
调用validate
方法以获取结果:
final aValidName = "Ahmed";
final invalidName = "";
final nameValidator = NameValidator();
final validResult = nameValidator.validate(aValidName); // 返回有效
final invalidResult = nameValidator.validate(invalidName); // 返回无效,其原因属性为之前传递的负反馈类型。
你还可以混合使用StringRules
,它包含常见的规则如notEmpty
。
class NameValidator extends Validator<String, dynamic> with StringRules {
[@override](/user/override)
List<ValidationRule<String, dynamic>> get rules => [
notEmpty<String>(negativeFeedback: "This field can't be empty."),
max(
maxLength: 10,
negativeFeedback: "Name can't be more than 10 characters."),
ValidationRule(
ruler: (value) {
if (RegExp("[A-Za-z]").hasMatch(value)) {
return true;
}
return false;
},
negativeFeedback: "Name has to be in English"),
];
}
异步验证规则
你可以创建一个AsyncValidationRule
和一个AsyncValidator
,它们可以同时具有ValidationRule
和AsyncValidationRules
规则。
验证结果的方法
验证结果具有一些方便的方法,如when
、maybeWhen
、map
和maybeMap
。例如:
// 将验证结果对象映射到字符串或null,以便与TextFormField的验证函数一起使用。
nameValidator.validate(val).maybeMap(
invalid: (invalid) => invalid.reasons.first,
orElse: () => null,
);
// 基于验证结果进行副作用操作。
phoneValidator.validate(val).maybeWhen(
invalid: (reasons) {
// 显示一个对话框
},
orElse: () {
// 弹出当前屏幕
},
);
完整示例
以下是一个完整的示例代码,展示了如何在Flutter应用中使用generic_validator
插件进行表单验证。
import 'package:example/validators/platform_phone_validator.dart';
import 'package:example/validators/sign_up_form_validator.dart';
import 'package:example/sign_up_textfield.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Generic validator demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.grey)),
home: const SignUp(),
);
}
}
class SignUp extends StatefulWidget {
const SignUp({Key? key}) : super(key: key);
[@override](/user/override)
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
var signUpFormKey = GlobalKey<FormState>();
late final SignUpFormValidator formValidator;
String? phoneValidation;
final TextEditingController _phoneController = TextEditingController();
[@override](/user/override)
void initState() {
super.initState();
final platformPhoneValidator = PlatformPhoneValidatorImpl();
formValidator =
SignUpFormValidator(platformPhoneValidator: platformPhoneValidator);
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.black,
automaticallyImplyLeading: false,
title: const Text(
"Sign up",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Form(
key: signUpFormKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(
height: 40,
),
SignUpTextFormField(
labelText: "First Name",
icon: Icons.first_page,
validator: (val) =>
formValidator.nameValidator.validate(val!).maybeMap(
invalid: (invalid) => invalid.reasons.first,
orElse: () => null,
),
),
const SizedBox(
height: 30,
),
SignUpTextFormField(
labelText: "Last Name: ",
icon: Icons.last_page,
validator: (val) => formValidator.nameValidator
.validate(val!)
.maybeMap(
invalid: (invalid) => invalid.reasons.first,
orElse: () => null,
)),
const SizedBox(
height: 30,
),
SignUpTextFormField(
labelText: "Email Address: ",
icon: Icons.email,
validator: (val) => formValidator.emailValidator
.validate(val!)
.maybeMap(
invalid: (invalid) => invalid.reasons.first,
orElse: () => null,
),
),
const SizedBox(
height: 30,
),
SignUpTextFormField(
controller: _phoneController,
labelText: "Phone Number: ",
icon: Icons.contact_phone,
onChange: (val) async {
await validatePhone(val);
},
validator: (val) => phoneValidation,
),
const SizedBox(
height: 30,
),
SignUpTextFormField(
labelText: "Password: ",
icon: Icons.password,
validator: (val) => formValidator.passwordValidator
.validate(val!)
.maybeMap(
invalid: (invalid) => invalid.reasons.first,
orElse: () => null,
)),
const SizedBox(
height: 35,
),
SizedBox(
width: 200,
height: 50,
child: ElevatedButton(
onPressed: () async {
await validatePhone(_phoneController.text);
signUpFormKey.currentState?.validate();
},
style: ElevatedButton.styleFrom(
primary: Colors.black,
),
child: const Text(
"Sign Up",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w900),
)),
),
]),
),
),
),
));
}
Future<void> validatePhone(String val) async {
(await formValidator.phoneValidator.validate(val)).maybeWhen(
invalid: (reasons) {
setState(() {
phoneValidation = reasons.first;
});
},
orElse: () {
setState(() {
phoneValidation = null;
});
},
);
}
}
更多关于Flutter数据验证插件generic_validator的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter数据验证插件generic_validator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter中使用generic_validator
插件进行数据验证的示例代码。这个插件可以帮助你快速实现各种数据验证逻辑,比如邮箱、电话号码、密码强度等。
首先,你需要在你的pubspec.yaml
文件中添加generic_validator
依赖:
dependencies:
flutter:
sdk: flutter
generic_validator: ^x.y.z # 请替换为最新版本号
然后运行flutter pub get
来安装依赖。
接下来是一个简单的示例,演示如何使用generic_validator
进行数据验证。
import 'package:flutter/material.dart';
import 'package:generic_validator/generic_validator.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Data Validation Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: DataValidationScreen(),
);
}
}
class DataValidationScreen extends StatefulWidget {
@override
_DataValidationScreenState createState() => _DataValidationScreenState();
}
class _DataValidationScreenState extends State<DataValidationScreen> {
final _formKey = GlobalKey<FormState>();
String _email = '';
String _password = '';
String _errorMessage = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Data Validation Example'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: 'Email'),
validator: (value) {
if (!MultiValidator.email(value)) {
return 'Please enter a valid email address.';
}
return null;
},
onChanged: (value) {
setState(() {
_email = value;
});
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Password'),
validator: (value) {
if (!MultiValidator.length(value, min: 8)) {
return 'Password must be at least 8 characters long.';
}
if (!MultiValidator.hasNumber(value)) {
return 'Password must contain at least one number.';
}
return null;
},
obscureText: true,
onChanged: (value) {
setState(() {
_password = value;
});
},
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
if (_formKey.currentState!.validate()) {
// If form is valid, you can proceed with form submission
setState(() {
_errorMessage = '';
});
// Here you can add your form submission logic
print('Email: $_email');
print('Password: $_password');
} else {
// If form is invalid, show an error message
setState(() {
_errorMessage = 'Please fix the errors in the form.';
});
}
},
child: Text('Submit'),
),
SizedBox(height: 10),
Text(_errorMessage, style: TextStyle(color: Colors.red)),
],
),
),
),
);
}
}
在这个示例中,我们创建了一个简单的表单,包含两个字段:电子邮件和密码。我们使用TextFormField
来接受用户输入,并为其设置了validator
属性。在validator
中,我们使用了generic_validator
插件提供的MultiValidator
类来进行数据验证。
- 对于电子邮件字段,我们使用
MultiValidator.email(value)
来验证输入的电子邮件地址是否有效。 - 对于密码字段,我们使用
MultiValidator.length(value, min: 8)
来验证密码长度是否至少为8个字符,以及MultiValidator.hasNumber(value)
来验证密码中是否至少包含一个数字。
当用户点击提交按钮时,_formKey.currentState!.validate()
方法会被调用,它会遍历所有字段并触发相应的验证器。如果所有字段都验证通过,则表单提交成功;否则,会显示一个错误消息。
希望这个示例能帮助你理解如何在Flutter中使用generic_validator
插件进行数据验证。