Skip to content

Commit

Permalink
Added converter function support
Browse files Browse the repository at this point in the history
  • Loading branch information
ozziest committed Dec 24, 2023
1 parent 4ef60bd commit 4ac4a6a
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 5 deletions.
2 changes: 2 additions & 0 deletions src/Types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,5 @@ export type LanguageType =
| "zh";

export type Translation = Record<RuleType, string>;

export type Definition = Record<string, string | string[]>;
16 changes: 12 additions & 4 deletions src/helpers/validate.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { IContext, IOptions, IValidationResult } from "../Interface";
import { getMessage } from "../Locale";
import { ValidationResult } from "../Types";
import { Definition, ValidationResult } from "../Types";
import { toRuleDefinition } from "../Factory";
import { getValueViaPath } from "./getValueViaPath";
import { getOptions } from "../Options";

export const validate = async (
data: any,
definition: Record<string, string>,
definition: Definition,
options?: Partial<IOptions>
): Promise<IValidationResult> => {
const currentOptions: IOptions = {
Expand All @@ -31,7 +31,7 @@ export const validate = async (

const getResults = async (
data: any,
definition: Record<string, string>,
definition: Definition,
options: IOptions
) => {
let isValid = true;
Expand All @@ -42,7 +42,15 @@ const getResults = async (
for (const key in definition) {
fields[key] = true;
// Parsing the rules
const rules = toRuleNameArray(definition[key]).map(toRuleDefinition);
const params = definition[key];
let ruleGroup: string = "";
if (Array.isArray(params)) {
ruleGroup = params.join("|");
} else {
ruleGroup = params;
}

const rules = toRuleNameArray(ruleGroup).map(toRuleDefinition);

// Getting the value by the path
const value = getValueViaPath(data, key);
Expand Down
21 changes: 20 additions & 1 deletion tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { beforeAll, describe, expect, test } from "vitest";
import { setOptions, validate, setLocales, ILocale } from "../index";
import {
setOptions,
validate,
setLocales,
ILocale,
required,
email,
} from "../index";
import en from "../src/i18n/en.json";
import tr from "../src/i18n/tr.json";

Expand Down Expand Up @@ -152,4 +159,16 @@ describe("validate() function ", () => {
expect(result.isValid).toBe(false);
expect(result.errors.email[0].message).toBe("Alan bir e-posta olmalıdır.");
});

test("should be able to use the converters", async () => {
const data = {
email: "sample",
};
const rules = {
email: [required(), email()],
};

const result = await validate(data, rules);
expect(result.isValid).toBe(false);
});
});

0 comments on commit 4ac4a6a

Please sign in to comment.