Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

📏 Add specific length string schema #191

Merged
merged 5 commits into from
Mar 21, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/constants/validationSchemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,15 @@ export const positiveNumberSchema = (fieldName: string) => {
message: errorMessages.positiveNumber(fieldName),
});
};

export const specificLengthStringSchema = (
fieldName: string,
min: number,
max: number,
) => {
return z
.string()
.max(max, { message: errorMessages.maxLength(fieldName, max) })
.trim()
.min(min, { message: errorMessages.minLength(fieldName, min) });
};
33 changes: 33 additions & 0 deletions tests/unit/validation/validationSchemas.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { specificLengthStringSchema } from "@/constants/validationSchemas";
import { describe, expect, test } from "vitest";

describe("specificLengthStringSchema", () => {
const fieldName = "field";
const minLength = 1;
const maxLength = 500;
const schema = specificLengthStringSchema(fieldName, minLength, maxLength);

test("rejects empty string", () => {
expect(() => schema.parse("")).toThrow();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should test error messages, you can look at tests from trinity

});

test("rejects string with only spaces", () => {
expect(() => schema.parse(" ")).toThrow();
});

test("rejects string shorter than min length", () => {
expect(() => schema.parse("a".repeat(minLength - 1))).toThrow();
});

test("rejects string longer than max length", () => {
expect(() => schema.parse("a".repeat(maxLength + 1))).toThrow();
});

test("accepts string with length equal to min length", () => {
expect(schema.parse("a".repeat(minLength))).toBe("a".repeat(minLength));
});

test("accepts string with length equal to max length", () => {
expect(schema.parse("a".repeat(maxLength))).toBe("a".repeat(maxLength));
});
});
Loading