🌍 Internationalization (i18n)
For internationalization (e.g., localized error messages), you should use a reactive approach with computed(). This ensures that error messages update automatically whenever the language changes.
Standard Approach (Without i18n)
typescript
// Simple and quick — for forms with fixed messages
const form = createForm(initialValues, (r, define) =>
define({
email: r.required('Email is required').email('Invalid format'),
})
)Reactive Approach (With i18n)
typescript
// Reactive messages — update automatically on locale change
const form = createForm(
initialValues,
computed(() => {
const r = createRules()
return {
email: r.required(t('validation.required')).email(t('validation.email')),
}
})
)Full example with vue-i18n:
vue
<script setup lang="ts">
import { createForm, createRules } from '@sakhnovkrg/vue-form-validator'
import { useI18n } from 'vue-i18n'
import { computed } from 'vue'
const { t } = useI18n()
const form = createForm(
{ username: '', email: '', password: '' },
// using computed() instead of (r, define) => ...
computed(() => {
const r = createRules()
return {
username: r.required(t('validation.required')),
email: r.required(t('validation.required')).email(t('validation.email')),
password: r
.required(t('validation.required'))
.minLength(6, t('validation.minLength', { count: 6 })),
}
}),
{
onSubmit: async values => {
console.log('Form submitted:', values)
},
}
)
</script>
<template>
<form @submit.prevent="form.submit">
<input v-model="form.values.username" @blur="form.touch('username')" />
<span v-if="form.hasError('username')">{{ form.error('username') }}</span>
<input v-model="form.values.email" @blur="form.touch('email')" />
<span v-if="form.hasError('email')">{{ form.error('email') }}</span>
</form>
</template>