Skip to content

Commit

Permalink
shorthand label in object
Browse files Browse the repository at this point in the history
  • Loading branch information
Fernando committed Jun 19, 2024
1 parent 105f908 commit e9af726
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
6 changes: 3 additions & 3 deletions lib/rules/object.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,20 +50,20 @@ module.exports = function ({ schema, messages }, path, context) {

for (let i = 0; i < keys.length; i++) {
const property = keys[i];

const rule = this.getRuleFromSchema(subSchema[property]);

const name = escapeEvalString(property);
const safeSubName = identifierRegex.test(name) ? `.${name}` : `['${name}']`;
const safePropName = `parentObj${safeSubName}`;
const newPath = (path ? path + "." : "") + property;

const labelName = subSchema[property].label;
const labelName = rule.schema.label;
const label = labelName ? `'${escapeEvalString(labelName)}'` : undefined;

sourceCode.push(`\n// Field: ${escapeEvalString(newPath)}`);
sourceCode.push(`field = parentField ? parentField + "${safeSubName}" : "${name}";`);
sourceCode.push(`value = ${safePropName};`);
sourceCode.push(`label = ${label}`);
const rule = this.getRuleFromSchema(subSchema[property]);
const innerSource = `
${safePropName} = ${context.async ? "await " : ""}context.fn[%%INDEX%%](value, field, parentObj, errors, context, label);
`;
Expand Down
6 changes: 6 additions & 0 deletions test/rules/object.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,12 @@ describe("Test rule: object", () => {
expect(v.validate({foo:"bar"}, {$$root: true, type: "object", maxProps: 0, strict: "remove"})).toEqual([{actual: 1, field: undefined, message: "The object '' must contain 0 properties at most.", type: "objectMaxProps", expected: 0}]);
});

it("shorthand label",()=>{
const check = v.compile({ $$root: true, type: "object", props: { shorthand_label: "string|label:My Label" } });
const res = check({ shorthand_label: 123 });
expect(res[0].label).toEqual("My Label");

});

describe("Test sanitization", () => {

Expand Down
5 changes: 5 additions & 0 deletions test/validator.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,11 @@ describe("Test getRuleFromSchema method", () => {
expect(res2.schema).toEqual({ type: "array", optional: true, items: "string", min: 1 });
});

it("should convert label", () => {
const res = v.getRuleFromSchema("string|label:My Label");
expect(res.schema).toEqual({ type: "string", label: "My Label" });
});

});

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

0 comments on commit e9af726

Please sign in to comment.