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
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 2 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -785,7 +785,8 @@ declare module "fastest-validator" {
export type ValidationRule =
| ValidationRuleObject
| ValidationRuleObject[]
| ValidationRuleName;
| ValidationRuleName
| RegExp;

/**
* Definition for validation schema based on validation rules
Expand Down
5 changes: 5 additions & 0 deletions lib/validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,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) {
Expand Down
6 changes: 6 additions & 0 deletions test/validator.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)", () => {
Expand Down