diff --git a/README.md b/README.md index be9ab80..96935f7 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/index.d.ts b/index.d.ts index 46c964f..8a10e4a 100644 --- a/index.d.ts +++ b/index.d.ts @@ -785,7 +785,8 @@ declare module "fastest-validator" { export type ValidationRule = | ValidationRuleObject | ValidationRuleObject[] - | ValidationRuleName; + | ValidationRuleName + | RegExp; /** * Definition for validation schema based on validation rules diff --git a/lib/validator.js b/lib/validator.js index 47896f9..35f7deb 100644 --- a/lib/validator.js +++ b/lib/validator.js @@ -318,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) { diff --git a/test/validator.spec.js b/test/validator.spec.js index 74044c4..2f6520e 100644 --- a/test/validator.spec.js +++ b/test/validator.spec.js @@ -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)", () => {