Skip to content

Commit 714566f

Browse files
authored
Merge pull request #203 from erfanium/fix
(Bugfix) multiple custom validator bug #202
2 parents 5a75033 + 4199b35 commit 714566f

File tree

2 files changed

+45
-9
lines changed

2 files changed

+45
-9
lines changed

lib/validator.js

+4-3
Original file line numberDiff line numberDiff line change
@@ -419,11 +419,12 @@ class Validator {
419419
`;
420420
}
421421

422+
const result = "res_" + ruleVName;
422423
return `
423424
const ${ruleVName} = context.customs[${ruleIndex}];
424-
const res = ${ruleVName}.schema.${fnName}.call(this, ${vName}, ${ruleVName}.schema, "${path}", parent, context);
425-
if (Array.isArray(res)) {
426-
res.forEach(err => errors.push(Object.assign({ message: ${ruleVName}.messages[err.type], field }, err)));
425+
const ${result} = ${ruleVName}.schema.${fnName}.call(this, ${vName}, ${ruleVName}.schema, "${path}", parent, context);
426+
if (Array.isArray(${result})) {
427+
${result}.forEach(err => errors.push(Object.assign({ message: ${ruleVName}.messages[err.type], field }, err)));
427428
}
428429
`;
429430
}

test/validator.spec.js

+41-6
Original file line numberDiff line numberDiff line change
@@ -444,13 +444,9 @@ describe("Test custom validation v1", () => {
444444
}
445445
});
446446

447-
let check;
448-
const fn = jest.fn();
449-
450-
451447
it("should compile without error", () => {
452-
453-
check = v.compile({
448+
const fn = jest.fn();
449+
const check = v.compile({
454450
num: {
455451
type: "number",
456452
min: 10,
@@ -467,6 +463,20 @@ describe("Test custom validation v1", () => {
467463
});
468464

469465
it("should work correctly with custom validator", () => {
466+
const fn = jest.fn();
467+
const check = v.compile({
468+
num: {
469+
type: "number",
470+
min: 10,
471+
max: 15,
472+
integer: true,
473+
custom(value){
474+
fn(value);
475+
if (value % 2 !== 0) return [{ type: "evenNumber", actual: value }];
476+
}
477+
}
478+
});
479+
470480
const res = check({num: 12});
471481
expect(res).toBe(true);
472482
expect(fn).toBeCalledWith(12);
@@ -475,6 +485,31 @@ describe("Test custom validation v1", () => {
475485
expect(check({num: 18})[0].type).toEqual("numberMax");
476486
expect(check({num: 13})[0].type).toEqual("evenNumber");
477487
});
488+
489+
it("should work with multiple custom validators", () => {
490+
const fn = jest.fn();
491+
492+
const check = v.compile({
493+
a: {
494+
type: "number",
495+
custom(value){
496+
fn(value);
497+
if (value % 2 !== 0) return [{ type: "evenNumber", actual: value }];
498+
}
499+
},
500+
b: {
501+
type: "number",
502+
custom(value){
503+
fn(value);
504+
if (value % 2 !== 0) return [{ type: "evenNumber", actual: value }];
505+
}
506+
}
507+
});
508+
509+
const res = check({a: 12, b:10});
510+
expect(res).toBe(true);
511+
expect(fn).toBeCalledTimes(2);
512+
});
478513
});
479514

480515
describe("Test custom validation", () => {

0 commit comments

Comments
 (0)