Lab 03: Custom Validator
📖 Resources
Section titled “📖 Resources”🚀 Starter Code
Section titled “🚀 Starter Code”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.
📝 Instructions
Section titled “📝 Instructions”Step 1: Create Custom Validator
Section titled “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
Section titled “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
Section titled “Step 3: Display Custom Error”Show custom error message:
<mat-error *ngIf="albumForm.get('price')?.errors?.['priceEndingWith9']"> Price must end with 9</mat-error>
