zod-form-helpers
v0.1.0
Published
A comprehensive utility library for working with Zod schemas - extract field types, validation rules, generate form inputs, and handle errors
Maintainers
Readme
zod-form-helpers
A comprehensive utility library for working with Zod schemas. Extract field types, validation rules, generate form inputs, and handle errors with ease.
Features
- 🔍 Type Detection - Determine field types from Zod schemas
- ✅ Validation Rules - Extract min/max, patterns, and validation constraints
- 📝 Form Generation - Generate HTML input types, placeholders, and labels
- 🚨 Error Handling - Validate fields and extract user-friendly error messages
- 💪 TypeScript First - Full type safety with TypeScript support
- 🎯 Zero Dependencies - Only peer dependency on Zod
Installation
npm install zod-form-helpersyarn add zod-form-helperspnpm add zod-form-helpersRequirements
- Node.js >= 18.0.0
- Zod >= 3.0.0 (peer dependency)
Usage
Type Detection
import { z } from 'zod';
import { getFieldType, isStringField, isNumberField } from 'zod-form-helpers';
const schema = z.object({
name: z.string(),
age: z.number(),
email: z.string().email(),
});
// Get field type
const nameType = getFieldType(schema, 'name'); // "string"
const ageType = getFieldType(schema, 'age'); // "number"
// Type checking
isStringField(schema, 'name'); // true
isNumberField(schema, 'age'); // trueValidation Rules
import { z } from 'zod';
import {
isRequired,
isOptional,
getMinLength,
getMaxLength,
getMinValue,
getMaxValue,
hasEmailValidation,
} from 'zod-form-helpers';
const schema = z.object({
username: z.string().min(3).max(20),
age: z.number().min(18).max(100),
email: z.string().email(),
bio: z.string().optional(),
});
// Check if required
isRequired(schema, 'username'); // true
isOptional(schema, 'bio'); // true
// Get length constraints
getMinLength(schema, 'username'); // 3
getMaxLength(schema, 'username'); // 20
// Get value constraints
getMinValue(schema, 'age'); // 18
getMaxValue(schema, 'age'); // 100
// Check validation types
hasEmailValidation(schema, 'email'); // trueForm Generation
import { z } from 'zod';
import {
getInputType,
getPlaceholder,
getLabel,
getEnumOptions,
} from 'zod-form-helpers';
const schema = z.object({
email: z.string().email(),
age: z.number(),
role: z.enum(['admin', 'user', 'guest']),
});
// Get HTML input type
getInputType(schema, 'email'); // "email"
getInputType(schema, 'age'); // "number"
getInputType(schema, 'role'); // "select"
// Get field label
getLabel(schema, 'email'); // "Email"
getLabel(schema, 'age'); // "Age"
// Get enum options
getEnumOptions(schema, 'role'); // ["admin", "user", "guest"]Error Handling
import { z } from 'zod';
import {
validateField,
getErrorMessage,
getFieldErrors,
getAllErrors,
} from 'zod-form-helpers';
const schema = z.object({
email: z.string().email(),
age: z.number().min(18),
});
// Validate a single field
const emailValidation = validateField(schema, 'email', 'invalid-email');
if (!emailValidation.success) {
console.log(getErrorMessage(emailValidation.error));
// "Invalid email"
}
// Validate entire object
const result = schema.safeParse({ email: '[email protected]', age: 15 });
if (!result.success) {
// Get all errors
const allErrors = getAllErrors(result.error);
console.log(allErrors);
// { age: ["Number must be greater than or equal to 18"] }
// Get errors for specific field
const ageErrors = getFieldErrors(result.error, 'age');
console.log(ageErrors); // ["Number must be greater than or equal to 18"]
}API Reference
Type Detection
getFieldType(schema, field)- Get the type of a fieldisStringField(schema, field)- Check if field is stringisNumberField(schema, field)- Check if field is numberisBooleanField(schema, field)- Check if field is booleanisDateField(schema, field)- Check if field is dateisArrayField(schema, field)- Check if field is arrayisObjectField(schema, field)- Check if field is objectisEnumField(schema, field)- Check if field is enum
Validation Rules
isRequired(schema, field)- Check if field is requiredisOptional(schema, field)- Check if field is optionalisNullable(schema, field)- Check if field is nullablegetMinLength(schema, field)- Get minimum length constraintgetMaxLength(schema, field)- Get maximum length constraintgetMinValue(schema, field)- Get minimum value constraintgetMaxValue(schema, field)- Get maximum value constraintgetExactLength(schema, field)- Get exact length constraintgetPattern(schema, field)- Get regex pattern constrainthasEmailValidation(schema, field)- Check if has email validationhasUrlValidation(schema, field)- Check if has URL validationhasUuidValidation(schema, field)- Check if has UUID validation
Form Generation
getInputType(schema, field)- Get HTML input typegetEnumOptions(schema, field)- Get enum optionsgetDefaultValue(schema, field)- Get default valuegetPlaceholder(schema, field)- Get placeholder textgetLabel(schema, field)- Get field labelgetStep(schema, field)- Get step for number inputsisMultiple(schema, field)- Check if allows multiple values
Error Handling
validateField(schema, field, value)- Validate a single fieldgetErrorMessage(error)- Get formatted error messagegetErrorType(error)- Get error typegetFieldErrors(error, field)- Get errors for a specific fieldgetAllErrors(error)- Get all errors organized by fieldgetCustomErrorMessage(error)- Get custom error message if available
TypeScript Support
This library is written in TypeScript and provides full type safety:
import { z } from 'zod';
import { FieldName, ZodObjectSchema, FieldType } from 'zod-form-helpers';
const schema = z.object({
name: z.string(),
age: z.number(),
});
// Type-safe field names
type Fields = FieldName<typeof schema>; // "name" | "age"Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT
Author
Alexis MINEAUD
