Solution: Dynamic Validation
Execute a possible implementation of the dynamic validation assignment.
We'll cover the following...
Let's divide the solution code into blocks and describe each of them individually.
The form model
We start by creating an interface for the form model:
Press + to interact
import { FormControl } from "@angular/forms";export interface RegistrationForm {name: FormControl<string>;address: FormControl<string>;isAbroad: FormControl<boolean>;userProfile: FormControl<string>;}
The RegistrationForm
interface contains the fields needed for the form, allowing the use of strong types.
Template
The template doesn't contain much logic in this exercise.
Press + to interact
<!-- ... --><mat-form-field class="full-width"><mat-label>Address</mat-label><input matInput formControlName="address" /><mat-error *ngIf="registrationAddress?.hasError('required')">Field required!</mat-error><mat-error *ngIf="registrationAddress?.hasError('minlength')">The address must contain at least 5 characters!</mat-error><mat-error *ngIf="registrationAddress?.hasError('maxlength')">The address cannot be longer than 30 characters!</mat-error></mat-form-field><!-- ... -->
For the template, the most important part of the assignment is to define the validation errors. We need to list all possible errors for the address field as we assigned different validation rules to the same control.
The component
class
The component
class contains all the validation logic. It's also possible to achieve the ...