1.0.2 • Published 9 months ago
class-validator-factory v1.0.2
Class Validator Factory
A utility for creating a validated instance of a class-validator decorated object from a plain object. If validation fails, it throws a validation exception containing a detailed list of errors.
Usage
Here's a quick example to get started:
import { IsDateString, IsNotEmpty, MaxLength, MinLength } from 'class-validator';
// Import the dependency
import { ClassValidatorFactory } from 'class-validator-factory';
// Example class with class validator decorators
class Example {
@MinLength(10, {
message: 'Title is too short',
})
@MaxLength(50, {
message: 'Title is too long',
})
title: string;
@IsDateString()
@IsNotEmpty()
timestamp: string;
}
// Object to be converted to a validated instance
const example = {
title: "Lorem ipsum dolor sit amet",
timestamp: Date.now().toLocaleString()
}
// Validation
const validExample: Example = new ClassValidatorFactory<Example>(Example).createInstance(example);
In the event of a validation error, the raised ValidationError
exception includes an errorList
property containing the forwarded errors generated by class-validator.
See Class Validator package for errors reference.
[
{
"target": {
"title": "Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet",
"timestamp": "Sun Dec 22 2024 01:07:45 GMT-0300 (Argentina Standard Time)"
},
"value": "Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet",
"property": "title",
"children": [],
"constraints": { "maxLength": "Title is too long" }
},
{
"target": {
"title": "Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet",
"timestamp": "Sun Dec 22 2024 01:07:45 GMT-0300 (Argentina Standard Time)"
},
"value": "Sun Dec 22 2024 01:07:45 GMT-0300 (Argentina Standard Time)",
"property": "timestamp",
"children": [],
"constraints": { "isDateString": "timestamp must be a valid ISO 8601 date string" }
}
]
Contributing
We welcome contributions! Here's how you can help:
- Fork the repository
- Create your feature branch: git checkout -b feature/your-feature
- Commit your changes: git commit -m 'Add your feature'
- Push to the branch: git push origin feature/your-feature
- Open a pull request
Feel free to reach out if you have questions, feedback, or feature requests. Contributions are always welcome! 🎉