Implementing form validation for mandatory fields upon submission in Angular 17

There are several fields such as firstName and lastName that are marked as required on the backend. If the form is submitted without entering the firstName, an error is displayed in the Network Preview. Similarly, if the firstName is filled but the lastName is left empty, another error is shown: lastName is required in the Network Preview:

{
    "status": "failed",
    "error": {
        "message": "Invalid request data. Please review the request and try again.",
        "code": [
            {
                "message": "firstName is required",
                "code": "any.required"
            }
        ]
    }
}

Below is the HTML:

<input type="text" class="form-control" [(ngModel)]="registration.firstName">
<input type="text" class="form-control" [(ngModel)]="registration.lastName">
<button type="button" class="btn btn-success" (click)="createRegistration(registration)">Submit</button>

I want to display the error message from the Network Preview when the Submit button is clicked:

<p>firstName is required</p>

Here is the TypeScript code:

createRegistration(registration:StudentRegistration){
    this.coreService.addRegistration(registration).subscribe({
      next: (res: any) => {
        this.registration = res.data || {} as StudentRegistration;
        this.opd.registration = res.data._id;
        this.createOpdStudent()
      },
      error: (err) => {
        console.log(err);
      }
    })
  }

I have explored frontend validation tutorials in Angular, but they require validating each field again on the frontend. I am looking for a backend validation solution similar to my case.

PS: Avoiding the frontend method as there are numerous forms with hundreds of fields

<p *ngIf="registration.firstName == '' || registration.firstName == undefined">First name is compulsory</p>

Answer №1

When handling errors in the error callback, you can retrieve the error message using the following method:

errorMessages: string[] = [];
error: (err) => {
  console.log(err);

  let errorResponse = err.error;
  this.errorMessages = errorResponse.code.map((x: any) => x.message);
}

To display a set of errorMessages:

<div *ngFor="let errorMessage of errorMessages">
  {{ errorMessage }}
</div>

If you want to display error messages based on different field sections, you'll need to implement a function to retrieve error messages based on the field name:

<div [ngClass]="{'show': hasError('firstName'), 'hide': !hasError('firstName')}">
  <span>FirstName error</span>
  <div *ngFor="let errorMessage of getErrorsByField('firstName')">
    {{ errorMessage }}
  </div>
</div>
hasError(fieldName: string) {
  return this.errorMessages.some((x) => x.indexOf(fieldName) > -1);
}

getErrorsByField(fieldName: string) {
  return this.errorMessages.filter((x) => x.indexOf(fieldName) > -1);
}

Check out the Demo on StackBlitz

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

When defining a class property in TypeScript, you can make it optional by not providing

Is there a way to make a property on a Class optional without it being undefined? In the following example, note that the Class constructor takes a type of itself (this is intentional) class Test { foo: number; bar: string; baz?: string; construc ...

"What is the method for verifying if a value is not a number in Angular 2

While attempting the following: dividerColor="{{isNaN(+price) ? 'warn' : 'primary'}}" An error is being thrown: browser_adapter.ts:82 ORIGINAL EXCEPTION: TypeError: self.context.isNaN is not a function Is there a way to determine ...

Angular2 implementation of scroll spy feature for CKEditor

I have a file loaded in CKEditor with a side menu located outside the editor. I'm looking to dynamically highlight specific items in the side navigation as different sections of the document are scrolled through. details.component.ts focusFunction() ...

Creating a Typescript interface with at least one specified type

I've recently delved into using typescript. Currently, I'm faced with a scenario where I need to import available types from backend endpoints. In one specific instance, an endpoint can support two types as parameters. Example: interface B ext ...

What is the best approach for looping through a JSON object?

Currently constructing a project using Angular and incorporating redux. In my JSON object, there are nested objects with specific values. Let's imagine: name: "john", sex: "m" children: [ { name: "joe", sex: "m" children: [ { name: " ...

Informing ng2-bootstrap's Timepicker of the invalidation

I have integrated ng2-bootstrap's timepicker component into my project. To enhance user experience, I created a custom validation function that is triggered by the ngModelChange() event. However, the timepicker component also comes with its own built- ...

Issue with TypeScript: Error appears when importing express after running "npm i @types/express -D"

Struggling with adding the following line of code in an index.ts file: import express, { Application } from 'express'; Initially encountered an error with "from 'express'", so I ran npm i @types/express -D which fixed that is ...

Utilizing a responsive design with a bootstrap grid system, featuring expandable columns for

After creating a bootstrap grid page, I am facing an issue with the layout on mobile screens. My problem arises when trying to reorder the cards properly for mobile view. Here is my current logic: <div class="row"> <div *ngFor="let col of [1, ...

What is the best way to retrieve the most recent emitted value using a BehaviorSubject in a different component?

When using BehaviorSubject, I encounter an issue where I can get the last emitted value in the same component, but after navigating to another component, I only receive the default value instead of the last emitted value. I implemented BehaviorSubject to ...

Strategies to prevent page refresh following a CSS modification in Ionic/angular

Working with ionic4 (angular6) and livereload here. What I Need - The ability to instantly load CSS in the browser without having to refresh the entire page. Can this be done? ...

Verifying TypeScript errors before each commit in a Vue application

We have set up a git hook in our app using Husky for pre-commit actions. Whenever someone commits code, it triggers the pre-commit code - #!/bin/sh . "$(dirname "$0")/_/husky.sh" export NVM_DIR="$HOME/.nvm" [ -s "$NVM_ ...

Executing functions in TypeScript

I am facing an issue while trying to call a function through the click event in my template. The error message I receive is "get is not a function". Can someone help me identify where the problem lies? This is my template: <button class="btn btn-prima ...

Ways to simulate a variable imported in the module being tested without it being a function parameter can be achieved by using describe.each and changing the mock value for each test

I have a requirement to test a function within my TypeScript module. module-to-test.ts import { config } from './app-config'; export const isSomethingWhatINeedSelector = createSelector( firstDependencySelector, secondDependencySelector ...

Receiving a TypeScript error when passing InnerRef on a styled-component forward

When forwarding innerRef to a styled-component like the example below, a type error occurs in typescript: interface MenuProps { isOpen: boolean } const BaseMenu = styled.ul<MenuProps>` padding: 0; /* ... styles ... */ ${({ isOpen }) => ...

Is there a way to denote a specific part of a generic type without explicitly specifying the parts as generics themselves?

My dilemma involves an object defined by a type from a 3rd party library: // Unable to modify this - it belongs to the 3rd party library; interface TypedEvent< TArgsArray extends Array<any> = any, TArgsObject = any > extends Event { args ...

Is there a way to determine the total number of angular components in my app using IntelliJ IDE?

Seeking a way to determine the total count of angular components using IntelliJ IDE. I attempted 'find in files' search tool with the terms "export class" but it retrieved more than just component files. Appreciate any help! =) Etienne. ...

What is the best way to have text wrap around an icon in my React application?

I am facing an issue while trying to display the note description over the trash icon in a React app. I have tried various methods but can't seem to achieve the desired effect. Can anyone guide me on how to get this layout? Here is what I intend to a ...

The requested resource could not be located at @angular/platform-browser.js

I am attempting to set up ASP.NET MVC 5 (not Core) + Angular 2.0.0 + JSPM + SystemJS + TS Loader. Upon running the application, I encounter the following error: Failed to load resource: the server responded with a status of 404 (Not Found) http://localho ...

There is no link between the two containers

I am facing an issue where two containers need to connect with each other. However, when attempting to fetch data from one container, I encounter an ENOTFOUND error. Surprisingly, this code functions properly on my local system but fails within the contain ...

What is the proper way to define a generic object interface in Typescript?

Within my code, I have constructs that resemble the following: { classNames: { foo: 'foo', .... bar: 'bar' }, method1: () => {....}, method2: () => {....}, stringKey1: 'stringKey1', ... stringK ...