Flutter数据验证插件valida_generator的使用
Flutter数据验证插件valida_generator的使用
在Flutter开发中,数据验证是一个常见的需求。valida_generator
是一个强大的插件,它允许开发者通过代码注解来生成数据验证逻辑。本文将详细介绍如何使用 valida_generator
插件进行数据验证。
安装与配置
首先,在项目的 pubspec.yaml
文件中添加以下依赖:
dependencies:
valida: ^0.0.1
dev_dependencies:
build_runner: <latest>
valida_generator: ^0.0.1
然后运行以下命令以安装依赖并生成验证代码:
dart pub get
接下来,创建你的模型类,并执行 build_runner
来生成验证代码。
创建模型类
以下是一个示例模型类 FormTest
,其中包含多个字段及其验证规则:
import 'package:valida/valida.dart';
part 'form_test.g.dart'; // 自动生成的文件
@Valida(nullableErrorLists: true, customValidate: FormTest._customValidate)
class FormTest {
static List<ValidaError> _customValidate(FormTest value) {
return [];
}
@ValidaString(
minLength: 15,
maxLength: 50,
matches: r'^[a-zA-Z]+$',
customValidate: _customValidateStr,
)
final String longStr;
@ValidaString(maxLength: 20, contains: '@')
final String shortStr;
@ValidaNum(isInt: true, min: 0, customValidate: FormTest._customValidateNum)
final num positiveInt;
static List<ValidaError> _customValidateNum(num value) {
return [];
}
@ValidaFunction()
static List<ValidaError> _customValidate2(FormTest value) {
return [
if (value.optionalDecimal == null && value.identifier == null)
ValidaError(
errorCode: 'CustomError.not',
message: 'CustomError message',
property: 'identifier',
value: value,
)
];
}
@ValidaFunction()
List<ValidaError> _customValidate3() {
return _customValidate2(this);
}
@ValidaNum(
min: 0,
max: 1,
comp: ValidaComparison<num>(
less: CompVal(0),
moreEq: CompVal.list([CompVal.ref('positiveInt')]),
),
)
final double? optionalDecimal;
@ValidaList(minLength: 1, each: ValidaString(isDate: true, maxLength: 3))
final List<String> nonEmptyList;
@ValidaString(isUUID: UUIDVersion.v4)
final String? identifier;
final NestedField? nested;
const FormTest({
required this.longStr,
required this.shortStr,
required this.positiveInt,
required this.optionalDecimal,
required this.nonEmptyList,
required this.identifier,
this.nested,
});
}
List<ValidaError> _customValidateStr(String value) {
return [
if (value == 'WrongValue')
ValidaError(
errorCode: 'CustomError.wrong',
message: 'WrongValue is not allowed',
property: 'longStr',
value: value,
),
];
}
执行代码生成
运行以下命令以生成验证代码:
dart pub run build_runner watch --delete-conflicting-outputs
使用验证函数
生成的验证函数可以用于验证模型实例。以下是如何使用 validateFormTest
函数进行验证的示例:
import 'form_test.dart';
void main() {
const form = FormTest(
longStr: 'long Str',
shortStr: 'shortStr',
positiveInt: 2.4,
optionalDecimal: 3,
nonEmptyList: [],
identifier: 'identifier',
);
final FormTestValidation validation = validateFormTest(form);
assert(validation is Validation<FormTest, FormTestField>);
expect(validation.numErrors, validation.allErrors.length);
expect(validation.hasErrors, true);
final errorsMap = validation.errorsMap;
expect(errorsMap.isNotEmpty, true);
expect(errorsMap[FormTestField.longStr]?.length, 2);
expect(validation.fields.longStr!.length, 2);
expect(errorsMap[FormTestField.shortStr]?.length, 1);
expect(validation.fields.shortStr!.length, 1);
expect(errorsMap[FormTestField.positiveInt]?.length, 1);
expect(validation.fields.positiveInt!.length, 1);
expect(errorsMap[FormTestField.nonEmptyList]?.length, 1);
expect(validation.fields.nonEmptyList!.length, 1);
expect(errorsMap[FormTestField.optionalDecimal]?.length, 2);
expect(validation.fields.optionalDecimal!.length, 2);
}
自定义验证
除了内置的验证规则外,还可以通过自定义验证函数来实现更复杂的验证逻辑。例如:
static List<ValidaError> _customValidate(FormTest value) {
return [];
}
更多关于Flutter数据验证插件valida_generator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter数据验证插件valida_generator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
valida_generator
是一个 Flutter 插件,用于自动生成数据验证代码。它可以帮助开发者减少手写验证逻辑的工作量,提高开发效率。以下是如何使用 valida_generator
的基本步骤:
1. 添加依赖
首先,在 pubspec.yaml
文件中添加 valida_generator
和 valida
的依赖:
dependencies:
valida: ^0.0.1
dev_dependencies:
valida_generator: ^0.0.1
build_runner: ^2.1.0
然后运行 flutter pub get
来安装依赖。
2. 创建数据模型
创建一个数据模型类,并使用 @Valida
注解来标记需要验证的字段。例如:
import 'package:valida/valida.dart';
part 'user_model.g.dart';
@Valida()
class UserModel {
final String username;
final String email;
final int age;
UserModel({
required this.username,
required this.email,
required this.age,
});
}
3. 生成验证代码
运行 build_runner
来生成验证代码:
flutter pub run build_runner build
这将会生成一个名为 user_model.g.dart
的文件,其中包含了自动生成的验证代码。
4. 使用生成的验证代码
生成的验证代码可以帮助你轻松验证数据模型。例如:
import 'user_model.dart';
void main() {
final user = UserModel(
username: 'john_doe',
email: 'john@example.com',
age: 25,
);
final validationResult = user.validate();
if (validationResult.isValid) {
print('User is valid');
} else {
print('Validation errors:');
validationResult.errors.forEach((field, errors) {
print('$field: $errors');
});
}
}
5. 自定义验证规则
你可以在 @Valida
注解中指定自定义的验证规则。例如:
@Valida(
rules: {
'username': [ValidaRule.required, ValidaRule.minLength(3)],
'email': [ValidaRule.required, ValidaRule.email],
'age': [ValidaRule.required, ValidaRule.min(18)],
},
)
class UserModel {
final String username;
final String email;
final int age;
UserModel({
required this.username,
required this.email,
required this.age,
});
}
6. 重新生成代码
如果你修改了验证规则或模型类,记得重新运行 build_runner
来更新生成的代码:
flutter pub run build_runner build