Skip to content

Commit

Permalink
fix: allow labels to be localized with names closes #4268
Browse files Browse the repository at this point in the history
  • Loading branch information
logaretm committed May 20, 2023
1 parent 675c63f commit 16580b4
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/real-dryers-drop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@vee-validate/i18n': patch
---

fix: allow labels to be localized with names closes #4268
10 changes: 9 additions & 1 deletion packages/i18n/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,18 @@ class Dictionary {
return this.container[locale]?.fields?.[field]?._default || this.container[locale]?.messages?._default;
}

public resolveLabel(locale: string, name: string, label?: string): string {
if (label) {
return this.container[locale]?.names?.[label] || label;
}

return this.container[locale]?.names?.[name] || name;
}

public format(locale: string, ctx: FieldValidationMetaInfo) {
let message!: ValidationMessageTemplate | undefined;
const { rule, form, label, name } = ctx;
const fieldName = label || this.container[locale]?.names?.[name] || name;
const fieldName = this.resolveLabel(locale, name, label);

if (!rule) {
message = this.getLocaleDefault(locale, name) || `${fieldName} is not valid`;
Expand Down
35 changes: 35 additions & 0 deletions packages/i18n/tests/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,41 @@ test('can define labels or names for fields', async () => {
expect(errors[1].textContent).toContain('Second test is required');
});

test('can define localized labels for fields', async () => {
configure({
generateMessage: localize('en', {
messages: { required: '{field} is required' },
names: {
first: 'First test',
second: 'Second test',
},
}),
});

const wrapper = mountWithHoc({
template: `
<div>
<Field name="first.value" label="first" :validateOnMount="true" rules="required" v-slot="{ field, errors }">
<input v-bind="field" type="text">
<span class="error">{{ errors[0] }}</span>
</Field>
<Field name="second.value" label="second" :validateOnMount="true" rules="required" v-slot="{ field, errors }">
<input v-bind="field" type="text">
<span class="error">{{ errors[0] }}</span>
</Field>
</div>
`,
});

await flushPromises();
const errors = wrapper.$el.querySelectorAll('.error');
expect(errors).toHaveLength(2);

expect(errors[0].textContent).toContain('First test is required');
expect(errors[1].textContent).toContain('Second test is required');
});

// #4164
test('can define labels or names for fields with useField', async () => {
let errorMessage!: Ref<string | undefined>;
Expand Down

0 comments on commit 16580b4

Please sign in to comment.