Skip to content

Lab 03: Custom Validator

step-3-album-wholesale-v16-post-add-album-form-array

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.

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 };
};
}

Add validator to FormControl:

albumForm = this.fb.group({
price: [0, [
Validators.required,
priceEndingWith9Validator() // Custom validator
]]
});

Show custom error message:

<mat-error *ngIf="albumForm.get('price')?.errors?.['priceEndingWith9']">
Price must end with 9
</mat-error>