https://github.com/evandersondev/zard
https://github.com/evandersondev/zard
Last synced: about 1 year ago
JSON representation
- Host: GitHub
- URL: https://github.com/evandersondev/zard
- Owner: evandersondev
- License: mit
- Created: 2025-03-16T21:47:15.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2025-03-16T21:56:38.000Z (over 1 year ago)
- Last Synced: 2025-03-16T22:17:31.623Z (over 1 year ago)
- Language: Dart
- Size: 0 Bytes
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# Zard 🧩
Zard is a schema validation and transformation library for Dart, inspired by the popular [Zod](https://github.com/colinhacks/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](https://buymeacoffee.com/evandersondev) 🌟. Your support helps us improve the framework and make it even better!
## Installation 📦
Add the following line to your `pubspec.yaml`:
```yaml
dependencies:
zard: ^0.0.5
```
Then, run:
```sh
flutter pub get
```
Or run:
```sh
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
```dart
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("example@example.com");
print("Parsed Value: $result"); // example@example.com
} 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
```dart
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
```dart
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
```dart
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
```dart
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
```dart
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:
1. **`parse()`**: Throws an exception if any validation fails.
2. **`safeParse()`**: Returns an object with a `success` flag 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()`**: Accepts `null` values 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](https://github.com/evandersondev/zard).
## License
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details.
---
Made with ❤️ for Dart/Flutter developers! 🎯✨