Lab 03 : Validateur Personnalisé
📖 Ressources
🚀 Code de Départ
step-3-album-wholesale-v16-post-add-album-form-array
Dans ce lab, vous allez créer une fonction de validation personnalisée pour appliquer une règle métier selon laquelle les prix des albums doivent se terminer par le chiffre 9. Vous allez implémenter la logique de validation, l'appliquer à un contrôle de formulaire et afficher des messages d'erreur personnalisés.
📝 Instructions
Étape 1 : Créer un Validateur Personnalisé
Créez une fonction de validation :
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function priceEndingWith9Validator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
if (!value) return null;
const endsWithNine = value.toString().endsWith('9');
return endsWithNine ? null : { priceEndingWith9: true };
};
}
Étape 2 : Appliquer au FormControl
Ajoutez le validateur au FormControl :
albumForm = this.fb.group({
price: [0, [
Validators.required,
priceEndingWith9Validator() // Validateur personnalisé
]]
});
Étape 3 : Afficher l'Erreur Personnalisée
Affichez le message d'erreur personnalisé :
<mat-error *ngIf="albumForm.get('price')?.errors?.['priceEndingWith9']">
Price must end with 9
</mat-error>