Lab 03: Custom Validator
π Resourcesβ
π Starter Codeβ
step-3-album-wholesale-v16-post-add-album-tags
In this lab, you'll create a custom validator function to enforce a business rule that album prices must end with the digit 9. You'll implement the validator logic, apply it to a form control, and display custom error messages.
π Instructionsβ
Step 1: Create Custom Validatorβ
Create a validator function:
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 };
};
}
Step 2: Apply to FormControlβ
Add validator to FormControl:
albumForm = this.fb.group({
price: [0, [
Validators.required,
priceEndingWith9Validator() // Custom validator
]]
});
Step 3: Display Custom Errorβ
Show custom error message:
<mat-error *ngIf="albumForm.get('price')?.errors?.['priceEndingWith9']">
Price must end with 9
</mat-error>