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 type definition for haltOnFirstError on Validator constructor | fix: #316 #322

Merged
merged 1 commit into from
Apr 23, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -912,6 +912,11 @@ export interface ValidatorConstructorOptions {
*/
considerNullAsAValue?: boolean;

/**
* Immediately halt after the first error
*/
haltOnFirstError?: boolean

/**
* Default settings for rules
*/
Expand Down
53 changes: 53 additions & 0 deletions test/typescript/validator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,59 @@ describe('TypeScript Definitions', () => {

});

describe("Test check generator with wrong obj and haltOnFirstError", () => {
const v = new Validator({ haltOnFirstError: true });

it("should give back one errors", () => {
const schema = {
id: { type: "number" },
name: { type: "string", min: 5, uppercase: true },
password: { type: "forbidden" }
};

let check = v.compile(schema);
let obj = { id: "string", name: "John", password: "123456" };

let res = check(obj);
expect(res).toBeInstanceOf(Array);
expect(res[0]).toEqual({
type: "number",
field: "id",
message: "The 'id' field must be a number.",
actual: "string",
});
expect(obj).toEqual({ id: "string", name: "John", password: "123456" });
});

it("should return true if no errors", () => {
const schema = {
id: { type: "number" },
name: { type: "string", min: 5, uppercase: true },
password: { type: "forbidden" }
};

let check = v.compile(schema);
let obj = { id: 5, name: "John Doe" };
let res = check(obj);
expect(res).toBe(true);
expect(obj).toEqual({ id: 5, name: "JOHN DOE" });
});

it("should return true if has valid in multi rule", () => {
const schema = {
status: [
{ type: "string", enums: ["active", "inactive"] },
{ type: "number", min: 0 }
]
};

let check = v.compile(schema);
expect(check({ status: "active" })).toBe(true);
expect(check({ status: 1 })).toBe(true);
expect(check({ status: false })).toEqual([{ "actual": false, "field": "status", "message": "The 'status' field must be a string.", "type": "string" }, { "actual": false, "field": "status", "message": "The 'status' field must be a number.", "type": "number" }]);
});
});

/*
describe("Test check generator with custom path & parent", () => {

Expand Down