easy_validation 0.0.1 easy_validation: ^0.0.1 copied to clipboard
A new Flutter package project.
Easy Validation #
EasyValidation provides many validators for Flutter, based on Dart plugin Respectable.
Get started #
First, you need to add the following dependencies to your 'pubspec.yaml':
dependencies:
reflectable: any
build_runner: any
easy_validation: any
How to use validators and validate a model #
Here is a simple usage example. Note that a lot of examples are available in unit test file test/easy_validation_test.dart
.
How to define a class model with validation:
import 'package:easy_validation/easy_validation.dart';
@easyValidation
class MyModel {
MyModel(this.firstname, this.lastname, this.gender, this.birthday, this.dateOfDeath);
@Required(error: 'Firstname is required')
@StringLength(min: 3, max: 32, error: 'Firstname must have between 3 and 32 characters')
final String firstname;
@Required(error: 'Lastname is required')
@StringLength(min: 3, max: 32, error: 'Lastname must have between 3 and 32 characters')
final String lastname;
@Required(error: 'Gender is required')
@StringLength(min: 1, max: 1, error: 'Gender must have 1 character')
final String gender;
@Required(error: 'Birthday is requried')
@DateTimeRange(min: '1900-01-01', max: null, error: 'Birthday must be betwwen 1900/01/01 and infinity')
final DateTime birthday;
@DateTimeRange(min: '1900-01-01', max: null, error: 'DateOfDeath must be betwwen 1900/01/01 and infinity')
@GreaterOrEqualTo(propertyName: 'birthday', error: 'DateOfDeath must be greater than Birthday')
final DateTime dateOfDeath;
}
Each time you add a validator and each time you update your model class, you must regenerate a mapping file of your models and validators. If this file is not generated and update after any change, EasyValidation won't work !
Use this command line to get the file to get a new file named *.reflectable.dart
.
> flutter packages pub run build_runner build
How to validate a model:
- Import the generated mapping file.
- Call
initializeReflectable
funtion.
import 'package:easy_validation/easy_validation.dart';
import 'package:*.reflectable.dart';
initializeReflectable();
MyModel tester = new MyModel('Maxime', 'AUBRY', 'M', DateTime.parse('1986-12-22'), null);
bool isValid = ModelState.isValid<MyModel>(tester);
if (isValid) {
// do stuff...
} else {
print(ModelState.errors);
}
Practice usage for Flutter with Blocs:
// Comming soon
Feature requests and bug reports #
Please file feature requests and bugs using the github issue tracker for this repository.