https://github.com/budarin/validate.ts
Object validation utils
https://github.com/budarin/validate.ts
Last synced: 15 days ago
JSON representation
Object validation utils
- Host: GitHub
- URL: https://github.com/budarin/validate.ts
- Owner: budarin
- License: mit
- Created: 2023-12-10T13:14:30.000Z (over 1 year ago)
- Default Branch: master
- Last Pushed: 2024-03-27T18:37:32.000Z (about 1 year ago)
- Last Synced: 2025-04-19T19:50:25.848Z (about 1 month ago)
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/@budarin/validate.ts
- Size: 43 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# validate.ts
Entities validation utils.
## Installation
```bash
yarn add @budarin/validate
```## Usage
```ts
import type { LikeExtended, FieldsValidators, ValidateEntity } from '@budarin/validate';import { validateEntity, isIntegerInRange, isStringWithLength } from '@budarin/validate.ts';
type User = {
name: string;
age: number;
};function getUser(obj: LikeExtended): User {
return {
name: obj.name,
age: obj.age,
};
}const userFields: FieldsValidators = {
name: {
validators: [[isStringWithLength(2, 50), 'The name must be a string between 2 and 50 characters long']],
required: true,
},
age: {
validators: [[isIntegerInRange(1, 100), 'The age must be an integer from 1 to 100']],
required: true,
},
};const validateUser: ValidateEntity = (data: unknown) => validateEntity(data, userFields, getUser, 'User');
const user = {
name: 'Ivan',
age: 30,
hair: 'brown',
};const validation = validateUser(user);
if (v.error) {
console.log(validation.error.message); // => 'The name must be a string between 2 and 50 characters long'
}console.log(validation.result); // => { name: 'Ivan', age: 30 }
```## List of utils
```
- hexColorvalidator
- validateEntity
- isUndefinedOr
- isInteger
- isIntegerInRange
- mustBeInt
- mustBeUndefinedOrInt
- isHexColor
- mustBeHexString
- hexColorValidator
- isStringWithLength
- isISODateTimeString
- stringHasWrongLength
- isBoolean
- mustBeUndefinedOrBoolean
- isObject
```## Exported types
```ts
export type Validator = (...args: any[]) => boolean;export type ValidateEntity = (data: unknown) => ResultOrError;
export type EntityGetter = (obj: LikeExtended) => DeepReadonly;export type FieldsValidators = {
[key: string]: {
validators: [Validator, string][];
required?: boolean;
};
};export type LikePartial = Partial;
export type LikeExtended = T & Partial>;
export type Like = T | (T & Partial>) | Partial;
export type AnyObject = Record;
```## License
MIT