https://github.com/commandstring/cmdstr-validation
An NPM package for simple validation of objects.
https://github.com/commandstring/cmdstr-validation
Last synced: 2 months ago
JSON representation
An NPM package for simple validation of objects.
- Host: GitHub
- URL: https://github.com/commandstring/cmdstr-validation
- Owner: CommandString
- Created: 2024-08-28T16:07:36.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2024-11-14T21:21:21.000Z (about 1 year ago)
- Last Synced: 2025-02-16T16:57:58.018Z (10 months ago)
- Language: TypeScript
- Homepage:
- Size: 41 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# [cmdstr-validation](https://github.com/commandstring/ts-validation)
A validation library for validating objects
## Installation
```
npm i cmdstr-validation
```
## Basic Usage
```js
const USERNAME_VALIDATOR = (new ValidationBuilder())
.addField('username', (builder) => builder
.makeRequired('You must have a username!')
.addTypeCheck(
(v: any) => typeof v !== 'string',
'Invalid username provided!'
)
.addValidator(
(v: string) => v.length > 50,
'Your username cannot exceed 50 characters!'
)
.addValidator(
(v: string) => v.length < 5,
'Your username must not be more than 5 characters!'
)
.addValidator(
(v: string) => (v.match(/^[a-z_1-9]+$/i) === null),
'Your username may only contain letters, underscores, and numbers!'
)
)
let usernameErrorBag = USERNAME_VALIDATOR.validate({username: 'Command_String'});
usernameErrorBag.hasErrors // false
usernameErrorBag.errors // {}
usernameErrorBag = USERNAME_VALIDATOR.validate({username: '$Co'});
usernameErrorBag.hasErrors // true
usernameErrorBag.errors /*
{
username: [
'Your username may only contain letters, underscores, and numbers!',
'Your username must be more than 5 characters!
]
}
*/
usernameErrorBag = USERNAME_VALIDATOR.validate({});
usernameErrorBag.hasErrors // true
usernameErrorBag.errors /*
{
username: [
'You must have a username!',
]
} */
```
*For more complex usage please see the unit tests in `/src/tests/validate.test.ts`*