Skip to content

Commit

Permalink
feat(validator): add enum validation to Validator class to support en…
Browse files Browse the repository at this point in the history
…um type fields
  • Loading branch information
Codycody31 committed Jan 8, 2024
1 parent 6cabbcd commit 5b5dc8f
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
42 changes: 42 additions & 0 deletions __tests__/validator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
);
});
});
20 changes: 19 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ interface Rule {
* Regular expression to validate the field.
*/
regex?: RegExp;
/**
* Enumeration of valid values.
*/
enum?: Array<string | number | boolean>;
}

/**
Expand Down Expand Up @@ -76,6 +80,10 @@ interface Message {
* The error message for regex validation failure.
*/
regex?: string;
/**
* The error message for invalid enum value.
*/
enum?: string;
}

/**
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -447,4 +465,4 @@ export type {
};

// Export class
export default Validator;
export default Validator;

0 comments on commit 5b5dc8f

Please sign in to comment.