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

Custom validation for built-in rules #119

Merged
merged 4 commits into from
Mar 21, 2020
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
2 changes: 2 additions & 0 deletions examples/full.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ const schema = {
apikey: "forbidden",
uuidv4: { type: "uuid", version: 4 },
uuid: "uuid",
phone: { type: "string", length: 15, custom: v => v.startsWith("+") ? true : [{ type: "wrongPhoneFormat" }] },
action: "function",
created: "date",
now: { type: "date", convert: true }
Expand Down Expand Up @@ -86,6 +87,7 @@ const obj = {
apikey: null,
uuidv4: "10ba038e-48da-487b-96e8-8d3b99b6d18a",
uuid: "10ba038e-48da-487b-96e8-8d3b99b6d18a",
phone: "+36-70-123-4567",
action: () => {},
created: new Date(),
now: Date.now()
Expand Down
10 changes: 9 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,14 @@ declare module 'fastest-validator' {
*/
default?: any;

/**
*
* @param {{any}} value Value that should be validated
* @param {ValidationRuleObject} schema Validation schema that describes current custom validator
* @return {{true} | ValidationError[]} true if result is valid or array of validation error messages
*/
custom?: (value: unknown, schema: ValidationRuleObject, path: string, parent?: object, context?: any) => true | ValidationError[];

/**
* You can define any additional options for custom validators
*/
Expand Down Expand Up @@ -772,7 +780,7 @@ declare module 'fastest-validator' {
* @param {string} name
* @param validationRule
*/
alias(name: string, validationRule: ValidationRule): void;
alias(name: string, validationRule: ValidationRule): void;

/**
* Build error message
Expand Down
3 changes: 2 additions & 1 deletion lib/rules/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

/** Signature: function(value, field, parent, errors, context)
*/
module.exports = function({ schema, messages }, path, context) {
module.exports = function({ schema, messages, customValidation }, path, context) {
const src = [];

src.push(`
Expand Down Expand Up @@ -99,6 +99,7 @@ module.exports = function({ schema, messages }, path, context) {
}

src.push(`
${customValidation("value")}
return value;
`);

Expand Down
4 changes: 3 additions & 1 deletion lib/rules/boolean.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

/** Signature: function(value, field, parent, errors, context)
*/
module.exports = function({ schema, messages }, path) {
module.exports = function({ schema, messages, customValidation }, path) {
const src = [];
let sanitized = false;

Expand Down Expand Up @@ -37,6 +37,8 @@ module.exports = function({ schema, messages }, path) {
if (typeof value !== "boolean")
${this.makeError({ type: "boolean", actual: "origValue", messages })}

${customValidation("value")}

return value;
`);

Expand Down
4 changes: 3 additions & 1 deletion lib/rules/date.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

/** Signature: function(value, field, parent, errors, context)
*/
module.exports = function({ schema, messages }, path) {
module.exports = function({ schema, messages, customValidation }, path) {
const src = [];
let sanitized = false;

Expand All @@ -23,6 +23,8 @@ module.exports = function({ schema, messages }, path) {
if (!(value instanceof Date) || isNaN(value.getTime()))
${this.makeError({ type: "date", actual: "origValue", messages })}

${customValidation("value")}

return value;
`);

Expand Down
4 changes: 3 additions & 1 deletion lib/rules/email.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const BASIC_PATTERN = /^\S+@\S+\.\S+$/;

/** Signature: function(value, field, parent, errors, context)
*/
module.exports = function({ schema, messages }, path) {
module.exports = function({ schema, messages, customValidation }, path) {
const src = [];

const pattern = schema.mode == "precise" ? PRECISE_PATTERN : BASIC_PATTERN;
Expand All @@ -29,6 +29,8 @@ module.exports = function({ schema, messages }, path) {
if (!${pattern.toString()}.test(value))
${this.makeError({ type: "email", actual: "value", messages })}

${customValidation("value")}

return value;
`);

Expand Down
4 changes: 3 additions & 1 deletion lib/rules/enum.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@

/** Signature: function(value, field, parent, errors, context)
*/
module.exports = function({ schema, messages }, path) {
module.exports = function({ schema, messages, customValidation }, path) {
const enumStr = JSON.stringify(schema.values || []);
return {
source: `
if (${enumStr}.indexOf(value) === -1)
${this.makeError({ type: "enumValue", expected: "\"" + schema.values.join(", ") + "\"", actual: "value", messages })}

${customValidation("value")}

return value;
`
Expand Down
3 changes: 2 additions & 1 deletion lib/rules/equal.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

/** Signature: function(value, field, parent, errors, context)
*/
module.exports = function({ schema, messages }, path) {
module.exports = function({ schema, messages, customValidation }, path) {
const src = [];

if (schema.field) {
Expand Down Expand Up @@ -34,6 +34,7 @@ module.exports = function({ schema, messages }, path) {
}

src.push(`
${customValidation("value")}
return value;
`);

Expand Down
5 changes: 4 additions & 1 deletion lib/rules/forbidden.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

/** Signature: function(value, field, parent, errors, context)
*/
module.exports = function checkForbidden({ schema, messages }, path) {
module.exports = function checkForbidden({ schema, messages, customValidation }, path) {
const src = [];

src.push(`
Expand All @@ -22,6 +22,9 @@ module.exports = function checkForbidden({ schema, messages }, path) {

src.push(`
}

${customValidation("value")}

return value;
`);

Expand Down
4 changes: 3 additions & 1 deletion lib/rules/function.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@

/** Signature: function(value, field, parent, errors, context)
*/
module.exports = function({ schema, messages }, path) {
module.exports = function({ schema, messages, customValidation }, path) {
return {
source: `
if (typeof value !== "function")
${this.makeError({ type: "function", actual: "value", messages })}

${customValidation("value")}

return value;
`
};
Expand Down
4 changes: 3 additions & 1 deletion lib/rules/luhn.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
*
* Signature: function(value, field, parent, errors, context)
*/
module.exports = function({ schema, messages }, path) {
module.exports = function({ schema, messages, customValidation }, path) {
return {
source: `
if (typeof value !== "string") {
Expand All @@ -34,6 +34,8 @@ module.exports = function({ schema, messages }, path) {
${this.makeError({ type: "luhn", actual: "value", messages })}
}

${customValidation("value")}

return value;
`
};
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/mac.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const PATTERN = /^((([a-f0-9][a-f0-9]+[-]){5}|([a-f0-9][a-f0-9]+[:]){5})([a-f0-9

/** Signature: function(value, field, parent, errors, context)
*/
module.exports = function({ schema, messages }, path) {
module.exports = function({ schema, messages, customValidation }, path) {
return {
source: `
if (typeof value !== "string") {
Expand All @@ -16,7 +16,7 @@ module.exports = function({ schema, messages }, path) {
if (!${PATTERN.toString()}.test(v)) {
${this.makeError({ type: "mac", actual: "value", messages })}
}

${customValidation("value")}
return value;
`
};
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/multi.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

/** Signature: function(value, field, parent, errors, context)
*/
module.exports = function({ schema, messages }, path, context) {
module.exports = function({ schema, messages, customValidation }, path, context) {
const src = [];

src.push(`
Expand Down Expand Up @@ -33,7 +33,7 @@ module.exports = function({ schema, messages }, path, context) {
if (hasValid) {
errors.length = prevErrLen;
}

${customValidation("newVal")}
return newVal;
`);

Expand Down
3 changes: 2 additions & 1 deletion lib/rules/number.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

/** Signature: function(value, field, parent, errors, context)
*/
module.exports = function({ schema, messages }, path) {
module.exports = function({ schema, messages, customValidation }, path) {
const src = [];

src.push(`
Expand Down Expand Up @@ -88,6 +88,7 @@ module.exports = function({ schema, messages }, path) {
}

src.push(`
${customValidation("value")}
return value;
`);

Expand Down
3 changes: 2 additions & 1 deletion lib/rules/object.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ function escapeEvalString(str) {

/** Signature: function(value, field, parent, errors, context)
*/
module.exports = function({ schema, messages }, path, context) {
module.exports = function({ schema, messages, customValidation }, path, context) {
const sourceCode = [];

sourceCode.push(`
Expand Down Expand Up @@ -101,6 +101,7 @@ module.exports = function({ schema, messages }, path, context) {
`);
} else {
sourceCode.push(`
${customValidation("value")}
return value;
`);
}
Expand Down
3 changes: 2 additions & 1 deletion lib/rules/string.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const ALPHADASH_PATTERN = /^[a-zA-Z0-9_-]+$/;

/** Signature: function(value, field, parent, errors, context)
*/
module.exports = function checkString({ schema, messages }, path, context) {
module.exports = function checkString({ schema, messages, customValidation }, path, context) {
const src = [];
let sanitized = false;

Expand Down Expand Up @@ -191,6 +191,7 @@ module.exports = function checkString({ schema, messages }, path, context) {
}

src.push(`
${customValidation("value")}
return value;
`);

Expand Down
4 changes: 3 additions & 1 deletion lib/rules/url.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const PATTERN = /^https?:\/\/\S+/;

/** Signature: function(value, field, parent, errors, context)
*/
module.exports = function({ schema, messages }, path) {
module.exports = function({ schema, messages, customValidation }, path) {
const src = [];
src.push(`
if (typeof value !== "string") {
Expand All @@ -18,6 +18,8 @@ module.exports = function({ schema, messages }, path) {
${this.makeError({ type: "url", actual: "value", messages })}
}

${customValidation("value")}

return value;
`);

Expand Down
14 changes: 13 additions & 1 deletion lib/validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,17 @@ class Validator {
this.cache.set(rule.schema, rule);
rule.index = context.index;
context.rules[context.index] = rule;
if (typeof rule.schema.custom === "function") {
context.customs[path] = { schema: rule.schema, messages: rule.messages };
rule.customValidation = value => `
const rule = context.customs["${path}"];
const res = rule.schema.custom.call(this, ${value}, rule.schema, "${path}", parent, context);
if (Array.isArray(res)) {
res.forEach(err => errors.push(Object.assign({ message: rule.messages[err.type], field }, err)));
}
`;
}

context.index++;
const res = rule.ruleFunction.call(this, rule, path, context);
if (res.source) {
Expand Down Expand Up @@ -296,7 +307,8 @@ class Validator {
const rule = {
messages: Object.assign({}, this.messages, schema.messages),
schema: schema,
ruleFunction: ruleFunction
ruleFunction: ruleFunction,
customValidation: () => ""
};

return rule;
Expand Down
40 changes: 40 additions & 0 deletions test/validator.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -365,4 +365,44 @@ describe("Test aliases", () => {
});
});

describe("Test custom validation for built-in rules", () => {
const v = new Validator({
messages: {
evenNumber: "The '{field}' field must be an even number! Actual: {actual}"
}
});

let check;
const fn = jest.fn();


it("should compile without error", () => {

check = v.compile({
num: {
type: "number",
min: 10,
max: 15,
integer: true,
custom(value){
fn(value);
if (value % 2 !== 0) return [{ type: "evenNumber", actual: value }];
}
}
});

expect(typeof check).toBe("function");
});

it("should work correctly with custom validator", () => {
const res = check({num: 12});
expect(res).toBe(true);
expect(fn).toBeCalledWith(12);

expect(check({num: 8})[0].type).toEqual("numberMin");
expect(check({num: 18})[0].type).toEqual("numberMax");
expect(check({num: 13})[0].type).toEqual("evenNumber");
});
});