From bfda31b8416698e827775450bcd59079334347da Mon Sep 17 00:00:00 2001 From: TomHermsen Date: Fri, 5 Jul 2024 14:31:33 +0200 Subject: [PATCH] Feat: More rules - Implemented nullable rules --- package.json | 2 +- src/Validator.ts | 6 ++++++ src/types/Rule.ts | 1 + tests/validator.test.ts | 36 ++++++++++++++++++++++++++++++++++++ 4 files changed, 44 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 79e4b19..c3e7108 100644 --- a/package.json +++ b/package.json @@ -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": { diff --git a/src/Validator.ts b/src/Validator.ts index 7d8bfe4..379089b 100644 --- a/src/Validator.ts +++ b/src/Validator.ts @@ -36,7 +36,13 @@ class Validator { } 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') { diff --git a/src/types/Rule.ts b/src/types/Rule.ts index 5f132f3..49eeba6 100644 --- a/src/types/Rule.ts +++ b/src/types/Rule.ts @@ -1,4 +1,5 @@ export type Rule = + | 'nullable' | 'required' | 'string' | `min:${number}` diff --git a/tests/validator.test.ts b/tests/validator.test.ts index 9011b81..664897b 100644 --- a/tests/validator.test.ts +++ b/tests/validator.test.ts @@ -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) + }) })