From 5b5dc8fbb872017b9e902c697a296ca9c2371fe7 Mon Sep 17 00:00:00 2001 From: Vahn Gomes Date: Mon, 8 Jan 2024 15:25:31 -0500 Subject: [PATCH] feat(validator): add enum validation to Validator class to support enum type fields --- __tests__/validator.test.ts | 42 +++++++++++++++++++++++++++++++++++++ src/index.ts | 20 +++++++++++++++++- 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/__tests__/validator.test.ts b/__tests__/validator.test.ts index 434e350..e07c6d3 100644 --- a/__tests__/validator.test.ts +++ b/__tests__/validator.test.ts @@ -556,3 +556,45 @@ describe("Validator - Specific Types", () => { expect(validator.getErrors().date).toBe("Expected a date"); }); }); + +describe("Validator - Enum", () => { + it("should throw when given a value not in the enum", () => { + const validator = new Validator( + { status: { enum: ["active", "inactive"] } }, + { status: { enum: "Expected a value in the enum" } } + ); + expect(validator.validate({ status: "deleted" })).resolves.toBe(false); + expect(validator.getErrors().status).toBe("Expected a value in the enum"); + }); + + it("should not throw when given a value in the enum", () => { + const validator = new Validator( + { status: { enum: ["active", "inactive"] } }, + { status: { enum: "Expected a value in the enum" } } + ); + expect(validator.validate({ status: "active" })).resolves.toBe(true); + expect(validator.getErrors().status).toBeUndefined(); + }); +}); + +describe("Validator - Input", () => { + it("should throw when given a non-object", () => { + const validator = new Validator( + { name: { type: "string" } }, + { name: { type: "Expected a string" } } + ); + expect(validator.validate("John Doe")).rejects.toThrow( + "Input must be an object" + ); + }); + + it("should throw when given a array", () => { + const validator = new Validator( + { name: { type: "string" } }, + { name: { type: "Expected a string" } } + ); + expect(validator.validate(["John Doe"])).rejects.toThrow( + "Input must be an object" + ); + }); +}); diff --git a/src/index.ts b/src/index.ts index a568b9b..59b1328 100644 --- a/src/index.ts +++ b/src/index.ts @@ -38,6 +38,10 @@ interface Rule { * Regular expression to validate the field. */ regex?: RegExp; + /** + * Enumeration of valid values. + */ + enum?: Array; } /** @@ -76,6 +80,10 @@ interface Message { * The error message for regex validation failure. */ regex?: string; + /** + * The error message for invalid enum value. + */ + enum?: string; } /** @@ -363,6 +371,16 @@ class Validator { isValid = false; } } + + // Enumeration validation + if (rule.enum && !rule.enum.includes(value)) { + this.errors[key] = + this.messages[key].enum ?? + `"${key}" must be one of the following values: ${rule.enum.join( + ", " + )}.`; + isValid = false; + } } // If strict mode is enabled, check for fields that are not defined in rules @@ -447,4 +465,4 @@ export type { }; // Export class -export default Validator; \ No newline at end of file +export default Validator;