zard 0.0.5
zard: ^0.0.5 copied to clipboard
Zard is a schema validation and transformation library for Dart, inspired by the popular Zod library for JavaScript.
Zard 🧩 #
Zard is a schema validation and transformation library for Dart, inspired by the popular Zod library for JavaScript. With Zard, you can define schemas to validate and transform data easily and intuitively.
Support 💖 #
If you find Zard useful, please consider supporting its development 🌟 Buy Me a Coffee 🌟. Your support helps us improve the framework and make it even better!
Installation 📦 #
Add the following line to your pubspec.yaml:
dependencies:
zard: ^0.0.5
Then, run:
flutter pub get
Or run:
dart pub add zard
Usage 🚀 #
Zard allows you to define schemas for various data types. Below are several examples of how to use Zard, including handling errors either by using parse (which throws errors) or safeParse (which returns a success flag and error details).
Defining Schemas #
String Example
import 'package:zard/zard.dart';
void main() {
// String validations with minimum and maximum length and email format check.
final schema = z.string().min(3).max(10).email(message: "Invalid email address");
// Using parse (throws if there is an error)
try {
final result = schema.parse("[email protected]");
print("Parsed Value: $result"); // [email protected]
} catch (e) {
print("Errors (parse): ${schema.getErrors()}");
}
// Using safeParse (doesn't throw; returns error info in result object)
final safeResult = schema.safeParse("Hi"); // "Hi" is too short
if (!safeResult['success']) {
safeResult['errors'].forEach((error) => print("Safe Error: $error")); // Output error messages 😱
} else {
print("Safe Parsed Value: ${safeResult['data']}");
}
}
Int Example
import 'package:zard/zard.dart';
void main() {
// Integer validations with minimum and maximum checks.
final schema = z.int().min(1).max(100);
// Using parse
try {
final result = schema.parse(50);
print("Parsed Value: $result"); // 50
} catch (e) {
print("Errors (parse): ${schema.getErrors()}");
}
// Using safeParse with error handling
final safeResult = schema.safeParse(5); // example: if 5 is below the minimum, it returns errors
if (!safeResult['success']) {
safeResult['errors'].forEach((error) => print("Safe Error: $error")); // Output error messages
} else {
print("Safe Parsed Value: ${safeResult['data']}");
}
}
Double Example
import 'package:zard/zard.dart';
void main() {
// Double validations with minimum and maximum checks.
final schema = z.doubleType().min(1.0).max(100.0);
try {
final result = schema.parse(50.5);
print("Parsed Value: $result"); // 50.5
} catch (e) {
print("Errors (parse): ${schema.getErrors()}");
}
final safeResult = schema.safeParse(0.5);
if (!safeResult['success']) {
safeResult['errors'].forEach((error) => print("Safe Error: $error")); // Outputs error message if invalid
} else {
print("Safe Parsed Value: ${safeResult['data']}");
}
}
Boolean Example
import 'package:zard/zard.dart';
void main() {
// Boolean validations
final schema = z.boolean();
try {
final result = schema.parse(true);
print("Parsed Value: $result"); // true
} catch (e) {
print("Errors (parse): ${schema.getErrors()}");
}
final safeResult = schema.safeParse(false);
if (!safeResult['success']) {
safeResult['errors'].forEach((error) => print("Safe Error: $error"));
} else {
print("Safe Parsed Value: ${safeResult['data']}");
}
}
List Example
import 'package:zard/zard.dart';
void main() {
// List validations with inner string schema validations.
final schema = z.list(z.string().min(3));
try {
final result = schema.parse(["abc", "def"]);
print("Parsed Value: $result"); // [abc, def]
} catch (e) {
print("Errors (parse): ${schema.getErrors()}");
}
final safeResult = schema.safeParse(["ab", "def"]); // "ab" is too short
if (!safeResult['success']) {
safeResult['errors'].forEach((error) => print("Safe Error: $error"));
} else {
print("Safe Parsed Value: ${safeResult['data']}");
}
}
Map Example
import 'package:zard/zard.dart';
void main() {
// Map validations combining multiple schemas
final schema = z.map({
'name': z.string().min(3).nullable(),
'age': z.int().min(1).nullable(),
});
try {
final result = schema.parse({
'name': 'John Doe',
'age': 30,
});
print("Parsed Value: $result"); // {name: John Doe, age: 30}
} catch (e) {
print("Errors (parse): ${schema.getErrors()}");
}
final safeResult = schema.safeParse({
'name': null,
'age': 0, // 0 might be invalid if min is greater than 0
});
if (!safeResult['success']) {
safeResult['errors'].forEach((error) => print("Safe Error: $error"));
} else {
print("Safe Parsed Value: ${safeResult['data']}");
}
}
Error Handling with ZardError 😵💫 #
When a validation fails, Zard provides detailed error information via the ZardError class. Each error object contains:
- message: A descriptive message about what went wrong.
- type: The type of error (e.g.,
min_error,max_error,type_error). - value: The unexpected value that failed validation.
Zard supports two methods for validation:
parse(): Throws an exception if any validation fails.safeParse(): Returns an object with asuccessflag and a list of errors without throwing exceptions.
New Methods & Functionality #
Zard now supports additional methods to handle optional and nullable values as well as partial map validations using .omit() and .pick().
.nullable(): Acceptsnullvalues and bypasses further validations..optional(): Marks the schema as optional; if a value is missing, validations are skipped..omit(): Excludes specific keys from being validated in a Map schema..pick(): Validates only a selected subset of keys in a Map schema.
Similarity to Zod #
Zard was inspired by Zod, a powerful schema validation library for JavaScript. Just like Zod, Zard provides an easy-to-use API for defining and transforming schemas. The main difference is that Zard is built specifically for Dart and Flutter, harnessing the power of Dart's language features.
Contribution #
Contributions are welcome! Feel free to open issues and pull requests on the GitHub repository.
License #
This project is licensed under the MIT License. See the LICENSE file for more details.
Made with ❤️ for Dart/Flutter developers! 🎯✨