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

feat: shorthand for regex #244

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
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
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -275,6 +275,14 @@ check({ foo: ["bar"] }) // true

### Nested objects

```js
const schema = {
code: /^[0-9]{6}$/,
phone: /^\+9\d{11}$/,
};
```

### Regex
```js
const schema = {
dot: {
@@ -294,6 +302,7 @@ const schema = {
};
```


# Alias definition
You can define custom aliases.

3 changes: 2 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
@@ -785,7 +785,8 @@ declare module "fastest-validator" {
export type ValidationRule =
| ValidationRuleObject
| ValidationRuleObject[]
| ValidationRuleName;
| ValidationRuleName
| RegExp;

/**
* Definition for validation schema based on validation rules
8 changes: 8 additions & 0 deletions lib/helpers/replace.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
function convertible(value) {
if (value === undefined) return "";
if (value === null) return "";
if (typeof value.toString === "function") return value;
return typeof value;
}

module.exports = (string, searchValue, newValue) => string.replace(searchValue, convertible(newValue));
22 changes: 15 additions & 7 deletions lib/validator.js
Original file line number Diff line number Diff line change
@@ -5,8 +5,8 @@ try {
AsyncFunction = (new Function("return Object.getPrototypeOf(async function(){}).constructor"))();
} catch(err) { /* async is not supported */}

//const flatten = require("./helpers/flatten");
const deepExtend = require("./helpers/deep-extend");
const replace = require("./helpers/replace");

function loadMessages() {
return Object.assign({} , require("./messages"));
@@ -167,7 +167,10 @@ class Validator {
async: schema.$$async === true,
rules: [],
fn: [],
customs: {}
customs: {},
utils: {
replace,
},
};
this.cache.clear();
delete schema.$$async;
@@ -205,11 +208,11 @@ class Validator {
sourceCode.push("if (errors.length) {");
sourceCode.push(`
return errors.map(err => {
if (err.message)
err.message = err.message
.replace(/\\{field\\}/g, err.field || "")
.replace(/\\{expected\\}/g, err.expected != null ? err.expected : "")
.replace(/\\{actual\\}/g, err.actual != null ? err.actual : "");
if (err.message) {
err.message = context.utils.replace(err.message, /\\{field\\}/g, err.field);
err.message = context.utils.replace(err.message, /\\{expected\\}/g, err.expected);
err.message = context.utils.replace(err.message, /\\{actual\\}/g, err.actual);
}

return err;
});
@@ -315,6 +318,11 @@ class Validator {
.every(rule => rule.schema.optional == true);
if (isOptional)
schema.optional = true;
} else if (schema instanceof RegExp) {
schema = {
type: "string",
pattern: schema
};
}

if (schema.$$type) {
21 changes: 21 additions & 0 deletions test/helpers/replace.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const replace = require("../../lib/helpers/replace");

describe("replace", () => {
it("should replace string", () => {
expect(replace("foo bar", "foo", "zoo")).toBe("zoo bar");
});

it("should replace if newValue is null or undefined", () => {
expect(replace("foo bar", "foo", undefined)).toBe(" bar");
expect(replace("foo bar", "foo", null)).toBe(" bar");
});

it("should replace if newValue has valid toString prototype", () => {
expect(replace("foo bar", "foo", { a: "b" })).toBe("[object Object] bar");
expect(replace("foo bar", "foo", ["a", "b"])).toBe("a,b bar");
});

it("should replace if newValue has invalid toString prototype", () => {
expect(replace("foo bar", "foo", { toString: 1 })).toBe("object bar");
});
});
17 changes: 17 additions & 0 deletions test/integration.spec.js
Original file line number Diff line number Diff line change
@@ -1285,3 +1285,20 @@ describe("Test context meta", () => {
expect(obj).toEqual({ name: "from-meta" });
});
});

describe("edge cases", () => {
const v = new Validator({ useNewCustomCheckerFunction: true });

it("issue #235 bug", () => {
const schema = { name: { type: "string" } };
const check = v.compile(schema);
expect(check({ name: { toString: 1 } })).toEqual([
{
actual: { toString: 1 },
field: "name",
message: "The 'name' field must be a string.",
type: "string",
},
]);
});
});
4 changes: 2 additions & 2 deletions test/typescript/validator.spec.ts
Original file line number Diff line number Diff line change
@@ -116,13 +116,13 @@ describe('TypeScript Definitions', () => {

check = v.compile(schema);

const context = {
const context = expect.objectContaining({
customs: expect.any(Object),
rules: expect.any(Array),
fn: expect.any(Array),
index: 2,
async: false
};
});

expect(validFn).toHaveBeenCalledTimes(1);
expect(validFn).toHaveBeenCalledWith(expect.any(Object), 'a', context);
10 changes: 8 additions & 2 deletions test/validator.spec.js
Original file line number Diff line number Diff line change
@@ -154,13 +154,13 @@ describe("Test add", () => {

check = v.compile(schema);

const context = {
const context = expect.objectContaining({
customs: expect.any(Object),
rules: expect.any(Array),
fn: expect.any(Array),
index: 2,
async: false
};
});


expect(validFn).toHaveBeenCalledTimes(1);
@@ -251,6 +251,12 @@ describe("Test getRuleFromSchema method", () => {
expect(res2.schema).toEqual({ type: "array", optional: true, items: "string", min: 1 });
});

it("should convert RegExp", () => {
const regex = /(foo)/;
const res = v.getRuleFromSchema(regex);
expect(res.schema).toEqual({ type: "string", pattern: regex });
});

});

describe("Test objects shorthand rule ($$type)", () => {