Skip to content

Commit

Permalink
Feat: More rules
Browse files Browse the repository at this point in the history
- Implemented nullable rules
  • Loading branch information
TomHermsen committed Jul 5, 2024
1 parent a702ac2 commit bfda31b
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "checkmate-ts",
"version": "1.0.3",
"version": "1.0.4",
"description": "Checkmate TypeScript - A powerful and flexible object validator written in TypeScript, supporting validation for various data types, nested objects, and arrays. Ensures type safety and reliability in data validation scenarios.",
"type": "module",
"exports": {
Expand Down
6 changes: 6 additions & 0 deletions src/Validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,13 @@ class Validator<R extends Rules> {
}

private validateField(key: string, value: any, rules: Rule[], errors: { [key: string]: string[] }) {
const isNullable = rules.includes('nullable')

rules.forEach(rule => {
if (isNullable && value == null) {
return // If the rule allows `null` values & the value is `null`, skip validating
}

if (rule === 'required') {
validateRequired(key, value, errors)
} else if (rule === 'string') {
Expand Down
1 change: 1 addition & 0 deletions src/types/Rule.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export type Rule =
| 'nullable'
| 'required'
| 'string'
| `min:${number}`
Expand Down
36 changes: 36 additions & 0 deletions tests/validator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,4 +202,40 @@ describe('Validator', () => {
const data = {tags: ['foo', 'test']}
expect(() => validator.validateObject(data)).toThrow(ValidationError)
})

test('should allow null on nullable string value', () => {
const validator = Validator.create({
'title': ['string', 'nullable'],
})

const data = {title: null}
expect(() => validator.validateObject(data)).not.toThrow(ValidationError)
})

test('should allow null on nullable array value', () => {
const validator = Validator.create({
'tags': ['array', 'nullable'],
})

const data = {tags: null}
expect(() => validator.validateObject(data)).not.toThrow(ValidationError)
})

test('should allow null on nullable number value', () => {
const validator = Validator.create({
'value': ['number', 'nullable'],
})

const data = {value: null}
expect(() => validator.validateObject(data)).not.toThrow(ValidationError)
})

test('should allow null on nullable numeric value', () => {
const validator = Validator.create({
'value': ['numeric', 'nullable'],
})

const data = {value: null}
expect(() => validator.validateObject(data)).not.toThrow(ValidationError)
})
})

0 comments on commit bfda31b

Please sign in to comment.