Setting up multi-language validation
I'm considering how to create a multi-language form validation system using Reactive Forms and Angular's built-in validators, plus some custom ones. The goal is to map dynamic error keys to internationalization (i18n) lines.
First, I plan to set up Angular i18n by adding the i18n attribute. Then, I'll create a validation error dictionary that references i18n markers. Since translation happens at compile time, I need to leverage template i18n markers to show error messages based on specific validation errors.Designing a multi-language validation system
I'm figuring out how to implement a multi-language form validation system. For standard error types, we can predefine messages, but for runtime key additions, it gets tricky.
Instead of repeating messages, I can create a <app-error-messages> component that takes care of known error keys and marks them with i18n. I would use Angular’s *ngIf to show appropriate error messages based on user input.
To enhance this, I should propose an architecture that involves using ReactiveForms and a service that returns the first error message, keeping translation in mind, even though i18n typically operates at the template level.Leveraging Angular's localization
I’m exploring how to use the new Angular $localize function, which works at runtime, although it still has compile-time aspects. This allows for dynamic messages with variables.
I could create a ValidationMessagesService to return appropriate error messages based on control status. For instance, using the $localize function to return localized messages for required fields or minlength errors is helpful. This allows us to extract messages from TypeScript, not just HTML, and I think it's a great way to serve up dynamic messages while utilizing Angular's i18n capabilities. It might be worth showing both template-based and service-based options.Planning error mapping with $localize
I’m thinking it would be better to use $localize for generating a mapping for error keys in Angular. My plan includes a few key steps.
First, I want to provide an overview, then focus on choosing the right infrastructure, specifically using Angular's built-in i18n with $localize for multiple locale builds.
Then I'll walk through an example scenario involving a form with name, email, and password fields, detailing the setup for i18n, creating a validation message service, and defining the error mappings with proper support for parameterized validation errors. Finally, I’ll suggest a reusable component for displaying these validation messages.Customizing field-specific error messages
I’m focusing on how to customize field-specific validation messages in Angular, perhaps by accepting a field label as a parameter. By injecting configuration via tokens, I can handle messages for different validators and leverage the i18n pipeline.
I also want to address edge cases like asynchronous validators and cross-field validation. It’s essential to note that Angular’s built-in i18n works at compile time. If the user is looking for a multi-language form validation system, I’ll provide both conceptual design and sample code, while keeping explanations manageable.
For dynamic messages, I can utilize $localize, and ensure to create a validation error service that generates localized messages using descriptive IDs. It might be simpler to keep validation messages generic, like "This field is required," to reduce complexity while accommodating different languages.Designing a reusable validation messages component
I’m focusing on creating a reusable component, <app-validation-messages>, that will handle field-specific validation error messages. The component uses Angular’s i18n features, employing the $localize function for translation, but it can also utilize the template-level approach for simplicity.
I see that using template-level i18n is generally easier for multi-language support in Angular, but both options are valid. The goal here is to provide a centralized error display component tied to the Angular validation system.
For a large form setup, I can rely on this component for each control, ensuring scalable and maintainable error handling. I’ll need to include example code and setup steps for localization to keep everything clear and accessible. Below is one concrete way to design a reusable, multi-language form‑validation system in Angular using the built‑in i18n (no ngx‑translate, no runtime translation library).
The core ideas:
- Centralize error messages in one reusable component.
- Map Angular validators (error keys) → human‑readable messages.
- Use Angular i18n (
i18n attribute and/or $localize) for translations.
- Let Angular build separate bundles per locale.
1. Prerequisites: Angular i18n setup
- Add the i18n package if not already there:
ng add @angular/localize
- Ensure
main.ts (or polyfills.ts in older projects) has:
import '@angular/localize/init';
- Configure locales in
angular.json (simplified):
{
"projects": {
"my-app": {
"i18n": {
"sourceLocale": "en",
"locales": {
"fr": "src/locale/messages.fr.xlf",
"de": "src/locale/messages.de.xlf"
}
}
}
}
}
2. Base form with Reactive Forms
Example: login form with email and password.
// login.component.ts
import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-login',
templateUrl: './login.component.html'
})
export class LoginComponent {
form = this.fb.group({
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(8)]],
});
constructor(private fb: FormBuilder) {}
}
<!-- login.component.html -->
<form [formGroup]="form" novalidate>
<label for="email" i18n="@@label_email">Email</label>
<input id="email" type="email" formControlName="email">
<app-control-errors [control]="form.get('email')"></app-control-errors>
<label for="password" i18n="@@label_password">Password</label>
<input id="password" type="password" formControlName="password">
<app-control-errors [control]="form.get('password')"></app-control-errors>
<button type="submit" [disabled]="form.invalid" i18n="@@btn_login">
Login
</button>
</form>
The interesting part is <app-control-errors> – that’s the reusable, i18n‑aware validation message component.
3. Reusable, i18n‑aware error component
3.1. Component class
// control-errors.component.ts
import { Component, Input } from '@angular/core';
import { AbstractControl, ValidationErrors } from '@angular/forms';
@Component({
selector: 'app-control-errors',
templateUrl: './control-errors.component.html',
})
export class ControlErrorsComponent {
@Input() control: AbstractControl | null = null;
get showErrors(): boolean {
const c = this.control;
return !!c && !!c.errors && (c.dirty || c.touched);
}
get errors(): ValidationErrors | null {
return this.control ? this.control.errors : null;
}
}
3.2. Component template (single source of truth for messages)
Here we map common validator keys to messages, and mark them for i18n:
<!-- control-errors.component.html -->
<ng-container *ngIf="showErrors && errors as e">
<!-- Required -->
<div *ngIf="e['required']" class="error" i18n="@@validation_required">
This field is required.
</div>
<!-- Email -->
<div *ngIf="e['email']" class="error" i18n="@@validation_email">
Please enter a valid email address.
</div>
<!-- Min length -->
<div *ngIf="e['minlength']" class="error" i18n="@@validation_minlength">
Minimum length is {{ e['minlength'].requiredLength }} characters.
</div>
<!-- Max length -->
<div *ngIf="e['maxlength']" class="error" i18n="@@validation_maxlength">
Maximum length is {{ e['maxlength'].requiredLength }} characters.
</div>
<!-- Pattern -->
<div *ngIf="e['pattern']" class="error" i18n="@@validation_pattern">
The value has an invalid format.
</div>
<!-- Example custom validator: passwordStrength -->
<div *ngIf="e['passwordStrength']" class="error" i18n="@@validation_passwordStrength">
Password must contain at least one uppercase letter and one number.
</div>
<!-- Fallback for unknown errors (optional) -->
<div *ngIf="!e['required'] && !e['email'] && !e['minlength'] && !e['maxlength']
&& !e['pattern'] && !e['passwordStrength']"
class="error" i18n="@@validation_generic">
The value is invalid.
</div>
</ng-container>
This template:
- Uses
i18n for each message so they’re extracted into the translation file.
- Uses interpolation for dynamic error data (
minlength.requiredLength, etc.).
- Centralizes all validation messages in one place.
Use this component anywhere you have a control:
<input formControlName="email">
<app-control-errors [control]="form.get('email')"></app-control-errors>
4. Custom validators with translatable errors
Define a custom validator that returns an error key you handle in ControlErrorsComponent.
// password-strength.validator.ts
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function passwordStrengthValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value as string;
if (!value) {
return null;
}
const hasUpperCase = /[A-Z]/.test(value);
const hasDigit = /[0-9]/.test(value);
return hasUpperCase && hasDigit ? null : { passwordStrength: true };
};
}
Use it in a form:
password: ['', [Validators.required, Validators.minLength(8), passwordStrengthValidator()]]
And we’ve already mapped passwordStrength in control-errors.component.html to an i18n message.
5. Optional: error messages from TypeScript via $localize
If you prefer not to hard‑code messages in HTML, you can centralize them in a service with $localize (still Angular i18n):
// validation-messages.service.ts
import { Injectable } from '@angular/core';
import { AbstractControl } from '@angular/forms';
@Injectable({ providedIn: 'root' })
export class ValidationMessagesService {
getErrorMessage(control: AbstractControl | null): string | null {
if (!control || !control.errors || !(control.dirty || control.touched)) {
return null;
}
const e = control.errors;
if (e['required']) {
return $localize`:@@validation_required:This field is required.`;
}
if (e['email']) {
return $localize`:@@validation_email:Please enter a valid email address.`;
}
if (e['minlength']) {
const required = e['minlength'].requiredLength;
return $localize`:@@validation_minlength:Minimum length is ${required} characters.`;
}
if (e['maxlength']) {
const required = e['maxlength'].requiredLength;
return $localize`:@@validation_maxlength:Maximum length is ${required} characters.`;
}
if (e['passwordStrength']) {
return $localize`:@@validation_passwordStrength:Password must contain at least one uppercase letter and one number.`;
}
return $localize`:@@validation_generic:The value is invalid.`;
}
}
Then your validation component template is very simple:
<!-- control-errors.component.html (alternative version) -->
<div *ngIf="message as m" class="error">{{ m }}</div>
// control-errors.component.ts (alternative version)
import { Component, Input } from '@angular/core';
import { AbstractControl } from '@angular/forms';
import { ValidationMessagesService } from './validation-messages.service';
@Component({
selector: 'app-control-errors',
templateUrl: './control-errors.component.html',
})
export class ControlErrorsComponent {
@Input() control: AbstractControl | null = null;
constructor(private messages: ValidationMessagesService) {}
get message(): string | null {
return this.messages.getErrorMessage(this.control);
}
}
Both approaches use Angular i18n; choose the one you prefer.
6. Extract and translate validation messages
- Extract messages:
ng extract-i18n --output-path src/locale
This produces messages.xlf (or .xlf2/.xmb depending on config) containing:
- Form labels
- Button texts
- Validation messages from component templates and/or
$localize strings.
- Copy
messages.xlf to locale files and translate:
cp src/locale/messages.xlf src/locale/messages.fr.xlf
cp src/locale/messages.xlf src/locale/messages.de.xlf
Edit messages.fr.xlf, messages.de.xlf, etc., and translate <target> for each <trans-unit> (including those with ids like @@validation_required).
- Build per locale:
ng build --localize
Angular will generate one build per locale (e.g., dist/my-app/fr, dist/my-app/de), each with all validation messages translated.
7. Summary of the design
- Centralization: one
ControlErrorsComponent (and optionally a ValidationMessagesService) that maps validator error keys to messages.
- Extensibility: add new validators by adding error keys + corresponding i18n messages in a single place.
- Internationalization: all messages marked with
i18n or $localize and extracted with ng extract-i18n.
- No duplication: same error definitions reused across all forms, all controls, all languages.
If you tell me your Angular version and whether you need runtime language switching (as opposed to per‑build), I can adjust this design accordingly.