I have implemented custom validators in an Angular form that I created. The validators are functioning correctly, but now I want to display an error message on the form indicating if there is a validation issue with the field.
After referring to this website (), which provided me with the initial validating code, I tried to follow their example to add error messages as well.
Here is a snippet of my HTML file:
<div class="container-fluid text-center">
<form [formGroup]="fg">
<div class="row">
<div class="col-3">
<div class="contactListArea">
<h2>Contacts</h2>
<ul id="list">
<li *ngFor="let contact of contacts;">
<button class="btn btn-primary" type="button" (click)="getContact(contact.id)">
<span class="name">{{contact.firstName}} {{contact.lastName}} </span>
</button>
</li>
</ul>
</div>
</div>
<div class="col-3">
<div class="row">
<div class="main-contact-list">
<div class="form-group mb-3 mr-5 mt-5">
<label class="mb-1">First Name</label>
<input class="form-control" type="text" class="form-control" [(ngModel)]="contact.firstName"
name="Name" formControlName="firstName" placeholder="Enter First Name">
</div>
`
Here is the TypeScript file where I created the validator:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function nameValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
if (!value) {
return null;
}
const nameValid = /[A-Z]{1,}[A-Za-z]{2,}/.test(value)
const noWhite = /^\S*$/.test(value);
const nameValidNoWhite = nameValid && noWhite
return !nameValidNoWhite ? { nameStrength: true } : null;
}
}
`
Lastly, here is the TypeScript file for my component where I added the validator to the form:
`
initForm(): void {
let id = Date.now() * Math.random();
this.fg = this.fb.group({
id: [id],
firstName: ['', [Validators.required, nameValidator()]],
lastName: ['', [Validators.required, nameValidator()]],
emailAddress: ['', [Validators.required, Validators.email]],
address1: ['', [Validators.required]],
address2: ['', [Validators.required]],
city: ['', [Validators.required]],
postCode: ['', [Validators.required, postCodeValidator()]],
});
}
`
When I attempt to add the error code to the form, it breaks. The screenshots below illustrate what happens: How the screen should look
What happens when I use the *ngIf statement: The outcome when the ngIf command is applied based on the tutorial website
Even after following the example provided in the web link and implementing the *ngIf statement to show the error message when requirements are not met, it still breaks the application.
I am unsure whether the part of the code (as shown in the example from the website): *ngIf="password.errors?.passwordStrength"
Should be the form control name for my chosen input?