dox_validation 3.0.0-alpha.5
dox_validation: ^3.0.0-alpha.5 copied to clipboard
Typed input for Dart. DTO classes with generated checks, fluent schemas like Zod, JSON Schema export and the Standard Schema interface.
dox_validation #
Typed input for Dart: DTO classes with generated checks, and fluent schemas like Zod.
Part of Dox, a web backend framework for Dart, like Laravel. Source code: github.com/dartondox/dox.
Install #
In a Dox app you do not add it. dox_core exports it. Outside Dox:
dart pub add dox_validation
dart pub add dev:dox_builder dev:build_runner
Dox 3.x is in alpha (3.0.0-alpha.4). The API can still change before the stable release.
Use it #
A DTO: a class with @Dto() and rule annotations. dox_builder writes the checks.
import 'package:dox_validation/dox_validation.dart';
part 'create_user.dto.g.dart';
@Dto()
class CreateUser {
@Length(min: 3, max: 50)
@Trim()
final String name;
@Email()
final String email;
const CreateUser({required this.name, required this.email});
static const DtoSchema<CreateUser> schema = $CreateUserDto;
}
Run dart run build_runner build. Then:
ParseResult<CreateUser> result = await CreateUser.schema.safeValidateMap(input);
if (!result.success) {
print(result.errors); // {'email': 'The email is not a valid email'}
}
A fluent schema, for input you only know at runtime:
final ObjectSchema createUser = v.object(<String, Schema<Object?>>{
'name': v.string().trim().min(3).max(50),
'email': v.string().email(),
'age': v.coerce.int().min(18).optional(),
});
Map<String, dynamic> data = createUser.parse(input); // throws ValidationException
Features #
- All problems come back at once, each with a path, a code and a message.
- Messages can change per rule, per call or for the whole app (for other languages).
v.coerceturns query and form text into numbers, booleans and dates.- Async checks with
refineAsyncandparseAsync. - JSON Schema (draft 2020-12) with
toJsonSchema(). OpenAPI uses it. - Every schema implements the Standard Schema interface.
- No dependencies.
Documentation #
License #
MIT. See LICENSE.