Angular Issue: Showing custom validator error messages

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?

Answer №1

After some tinkering, I successfully added an error message feature.

I've set up a validator for the 'Last Name' field which flags any entries that don't meet the specified criteria as errors.

In my HTML template, I inserted the following code snippet:

<span class="help-block"
*ngIf="fg.get('firstName')?.errors && fg.get('firstName')?.touched">
Your Name must have Upper Case starting letter and 3 characters. </span>

This code essentially accesses our form group variable (fg) and uses the get method to retrieve the form control named 'firstName'. If there are any errors or if the field has been touched, it will display the specified error message.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Efficiently processing a JSON object datalist in the AJAX success callback using JavaScript

I am having trouble parsing a JSON datalist in my AJAX success function. I have passed an object containing a list of data using JSON from the controller to the view, and now need help parsing the JSON object in the AJAX success function. Below is the code ...

send back the result to the primary function

I need help with this code. I'm trying to return the budget from callbacks in the main function. How can I return a value from the main function? // This method returns the current budget of the user getCurrentBudget: function (req) { var reqTok ...

Running res.render in an asynchronous manner within an express application

My goal is to make this router respond asynchronously: var express = require('express'), router = express.Router(); router.get('/', function(req, res, next) { res.render('contact', { titleShown: true, title: & ...

Confirm the default value in a text box

I am currently working with a textbox that I have set up as shown below: <div form="form-group"> <label for="Title"> <h3>Title:</h3> </label> <div [ngClass]="{ 'has-errors': (dataProcessingEditFo ...

Unexpected behavior encountered when using v-bind in conjunction with Math.random

I'm exploring the concept of generating random styles for an array of spans within a Vue component. By breaking down the message and utilizing v-for, I aim to showcase individual words in separate spans. const textFx = Vue.component('text-fx&apo ...

Am I implementing the Vue.JS onChange function correctly?

After selecting an option from mod_accs_Role_ID, how can I display the corresponding data stored in the database based on that selection? For example, if I select 1 in mod_accs_Role_ID, then the role_Name 'Hello' should be displayed. <div clas ...

What is the best way to retrieve the global styles.scss file from the assets folder for privacy, legal, and conditions pages

I have a static page called terms.html located at: $PROJECT_ROOT/src/assets/html/terms.html In addition, my global styles (used by all components) are found at: $PROJECT_ROOT/src/styles.scss To include the static html file in a component, I use the fol ...

"Trying to access jQuery .slide and .slideUp features, but unfortunately they are

I've created this script: $("#comments .comment .links").hide(); $("#comments .comment").hover( function() { $(".links", this).stop(true).slideDown(300); }, function() { $(".links", this).stop(true).slideUp(300); } ); However, I'm facin ...

Customizing the toolbar in MUI Datatable

Is there a way to customize the MUI-Datatable by moving the block within the red square into the toolbar and filling up the empty space? I could use some help with this task. ...

Navigating Users and Routing with Ionic Framework (AngularJS)

Currently, I am using Ionic for a new project and could use some guidance with routing (I'm relatively new to Angular). These are the states I have defined: $stateProvider.state('map', { url: '/map', views: { map: ...

Tips for displaying an object's properties using ngfor?

<div *ngFor="let article of articleList; let i = index"> <div class="item"> <div class="image-holder" style="background-image: url(https://uniqueblog.com/images/ninja-1.jpg)"&g ...

Stop prettier-standard from deleting semicolons within Typescript interfaces

In my current Typescript project, I have defined an interface called CurrencyAmountProps. interface CurrencyAmountProps { value: number; currency: string; } To format my Typescript files, I am using a command line tool called prettier-standard. The ...

jQuery toggle feature malfunctioning

I started creating a basic HTML page that includes some JavaScript and CSS: $('.expand').click(function() { $('.img_display_content').show(); }); @charset "utf-8"; /* CSS Document */ .wrap { margin-left: auto; margin-right: a ...

Do you find this unattractive? What are some ways to improve this unsightly JavaScript statement?

This code seems messy, how can I better structure this switch statement? function renderDataTypeIcon(dataType: string) { let iconName; switch (dataType) { case "STRING": //TODO - ENUM iconName = "text"; break; ...

It seems that an issue has occurred indicating that something is not defined in the current context

Hello everyone, I'm struggling with a problem that I just can't seem to figure out. I've tried multiple solutions but this error keeps popping up and now I'm completely lost. Can someone please help me resolve this issue? The code in q ...

Error: Import statement is not allowed outside of module scope

I've been through multiple documentations and sources, but I'm still struggling to fix this error. I recently started learning JavaScript and decided to experiment with fetch() commands, however, I keep encountering an issue (the title). Below i ...

Leveraging jQuery to manipulate an SVG file

jQuery is designed to work within HTML pages that contain JavaScript code. While SVG and HTML both use the same DOM Level 2, SVG is XML-based and employs ECMAScript. What potential issues could arise from utilizing jQuery with SVG? Is it more advisable t ...

Angular UI refresh triggered by database update

In my current setup, I have an angular application that interacts with a backend asp.net core web-API to retrieve data. The application allows multiple users to be logged in simultaneously. In the event that one user performs a specific action first, that ...

The code threw an error stating: "Error: Unable to set a new value to the unalterable property 'children' of the object '#<Object>'"

Encountering internal server error in Next.js build with Docker when reloading all routes with getServerSideProps react: "17.0.2" next: "^11.1.2" Local setup and deployment without Docker works fine, but with Docker implementation, reloading pages leads ...

How do Polymer elements and AngularJS directives differ from each other?

Exploring the Polymer Getting Started guide reveals a practical example showcasing Polymer's capabilities: <html> <head> <!-- 1. Shim missing platform features --> <script src="polymer-all/platform/platform.js"></ ...