ack 2.0.0-beta.4
ack: ^2.0.0-beta.4 copied to clipboard
Schema validation and bidirectional codecs for Dart and Flutter
// Validates a map against a schema, then exports the same schema as JSON
// Schema Draft-7. Run it with `dart run example/example.dart`.
import 'dart:convert';
import 'package:ack/ack.dart';
void main() {
final userSchema = Ack.object({
'name': Ack.string().minLength(2).maxLength(50),
'email': Ack.string().email(),
'age': Ack.integer().min(0).max(120).optional(),
});
final result = userSchema.safeParse({
'name': 'Ada Lovelace',
'email': 'ada@example.com',
'age': 36,
});
if (result.isOk) {
print('Valid user: ${result.getOrThrow()}');
} else {
print('Validation failed: ${result.getError()}');
}
// Root errors use # as their path.
print(
Ack.string().safeParse(42).getError(),
); // #: Expected string, got integer
// The missing field is reported at #/email.
final incomplete = userSchema.safeParse({'name': 'Ada'});
print(incomplete.getError());
// The same schema exports as JSON Schema Draft-7.
print(const JsonEncoder.withIndent(' ').convert(userSchema.toJsonSchema()));
}