Search code examples
vue.jsnuxt.jsvue-i18nnuxt-i18n

Vuetify rules message translation using nuxt i18n


I want to display translated rule messages, when Vuetify validation fails

Template section

<v-text-field
    v-model="message.name"
    outlined
    :label="$t('page.contact.form.name')"
    :rules=nameValidationRules
></v-text-field>

Script section

const nameValidationRules = ref([requiredRule, blankValidator])

Validator rules are kept in "validationRules.ts"

export const requiredRule = (value: any): string | boolean => !!value || 'This field is required';
export const blankValidator = (value: string | null | undefined): string | boolean => !value || !!value?.trim() || 'This field cannot be blank.';

I want to replace the 'This field is required' with i18n variable.


Solution

  • You could pass translation function to the rule definition :

    const {t} = useI18n()
    
    const nameValidationRules = ref([requiredRule(t), blankValidator(t)])
    
    export const requiredRule = (t: any) => (value: any): string | boolean => !!value || t('required');
    export const blankValidator = (t: any) => (value: string | null | undefined): string | boolean => !value || !!value?.trim() || t('not_blank');