A guide on triggering numerous alerts during validations in Javascript

My goal is to validate each form value with its own criteria and display an alert for each validation failure. While I am able to achieve this, the error messages are currently being shown on the same line, but I want them to be displayed on separate lines.

https://i.sstatic.net/TRJCp.png

In my console, I can see the correct answer for each error displayed on a different line.

I go through each validation criteria, collecting errors in an array. If the array is not empty, indicating we have errors, the error array is returned. Otherwise, the details are submitted to the backend API.

if(errors.length != 0){
      console.log("Not an empty array");
      console.log(errors.join('\r\n'));
      this.errorMsg = errors.join('\r\n');
    }else{
      this.service.createData(formData).subscribe((res) => {
        console.log(res);
        this.userForm.reset();
        this.successMsg = res.message;
      });
    }

.html

<div *ngIf="errorMsg" class="alert alert-danger alert-dismissible fade show" role="alert">
        <strong>{{errorMsg}}</strong> 
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>

Answer №1

The issue here is that all errors are being merged into a single variable called errorMessage. What should actually be done is to iterate through each error and display an alert for each one. The code snippet below demonstrates how this can be achieved:

<div class="alert alert-danger alert-dismissible fade show" role="alert" *ngFor="let error of errors">
  <strong>{{errorMsg}}</strong> 
  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>

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

What is the best way to rearrange the elements of an array based on a specific key value?

Is there a way to order the results of a Wordpress wp_query by post_status? I need to display private posts before other posts, but it doesn't seem to be an option. The array of posts looks like this: $posts = array( 0=>object{ ...

Monitor a universal function category

Trying to implement a TypeScript function that takes a single-argument function and returns a modified version of it with the argument wrapped in an object. However, struggling to keep track of the original function's generics: // ts v4.5.5 t ...

Node.js Azure Functions: My route parameters are not included in context.bindingData as the documentation implies

I'm currently working on a function that needs to retrieve 2 route parameters (first required, second optional), but I'm encountering some difficulties despite following the Documentation provided. I am specifically referring to this set of inst ...

Incorporate JavaScript to dynamically fetch image filenames from a directory and store them in an array

By clicking a button, retrieve the names of images from a folder and store them in an array using jQuery. I currently have a script that adds images to the body. In the directory images2, there are 20 images stored. The folder images2 is located in my i ...

Is it possible to remove the browsing history of user inputs in JavaScript?

I'm currently working on a Simon Says game where the level of difficulty increases as players correctly repeat the pattern. However, I encountered an issue with clearing the input history that shows previous patterns entered by the user. How can I res ...

Issues arise when trying to update the modelValue in unit tests for Vue3 Composition API

Recently delving into Vue, I am currently engaged in writing unit tests for a search component incorporated in my project. Basically, when the user inputs text in the search field, a small X icon emerges on the right side of the input box. Clicking this X ...

Blazor Server: Seamless breadcrumb navigation updates with JavaScript on all pages

I have implemented a breadcrumb feature in my Blazor Server project within the AppLayout that functions for all pages: <ul id="breadcrumbs" class="breadcrumbs"> <li><a href="#">Home</a></li> ...

Switching left navigation in material-ui when the user interacts within the application boundary

I am currently implementing a toggle feature in my AppBar to display the LeftNav. I have successfully set it up to close when the toggle is clicked again. However, I wish to mimic the behavior of most left nav bars where clicking anywhere outside of the ...

What could be causing my Apollo useLazyQuery to be triggered unexpectedly within a React hook?

import { useLazyQuery } from '@apollo/client'; import { useEffect, useState } from 'react'; import { ContestSessionResponseInfoObject, GetSessionDocument, HasAccessToRoundDocument, } from '@/graphql/generated/shikho-private- ...

The optimal organization of factories in AngularJS

I have a dilemma with my AngularJS single page application where I find myself calling the JSON file twice in each method $http.get('content/calendar.json').success(function(data) {.... Is there a more efficient way to make this call just once, ...

What is causing all Vuejs requests to fail in production with the error message "javascript enabled"?

My vuejs application interacts with a REST API in Node.js (Express, MongoDB Atlas). Everything runs smoothly when I run the Vue app on localhost while the Node.js app is on the server. However, when I deploy my dist folder to the server, although the app ...

Accessing website login - <div> and validating user entry

I am currently working on developing a basic login webpage, but I am facing issues with the rendering of the page. Below is the code I am using: function logIn(username, password){ var username = document.getElementById("username").value; var p ...

Utilize React to extract a JSON object nested within an array and then implement a dropdown sorting feature for the JSON

Can anyone help me figure out how to extract the eventId and title from the "currentSchedule" array nested within the main "response" array? I have successfully looped through all the data in the "response" array dynamically, ...

Is it possible for me to choose to establish a new scope within a directive?

Encountered an issue while reusing a directive where some tags had a second directive with a new scope created using new or {}, while others did not have one. Attempting to create a new scope when one already existed resulted in an error being thrown by An ...

Prevent AJAX request while in progress?

I've made some adjustments to a jQuery Autocomplete plugin, which now retrieves a JSON object from a MySQL database instead of an array. However, I've noticed that each time I click on the input field, it triggers a new request, even if it&apos ...

Develop a fresh Typescript-driven sql.js database

I'm in the process of converting my JavaScript code to TypeScript. One of the libraries I rely on is sql.js. I have successfully installed the corresponding typing for it, but I am facing a roadblock when it comes to creating the database. Here is ho ...

Angular 4's Mddialog experiencing intermittent display problem

While using MDDialog in my Angular app, I've encountered a couple of issues. Whenever a user clicks on the div, flickering occurs. Additionally, if the user then clicks on one of the buttons, the afterclose event is not triggered. Can anyone provide ...

I am interested in updating the content on the page seamlessly using Angular 6 without the need to reload

As a newcomer to Angular, I am interested in dynamically changing the page content or displaying a new component with fresh information. My website currently features cards, which you can view by following this Cards link. I would like to update the page ...

What is the purpose of `{ _?:never }` in programming?

I've been going through some TypeScript code and I stumbled upon a question. In the following snippet: type LiteralUnion<T extends U, U extends Primitive> = | T | (U & { _?: never }); Can anyone explain what LiteralUnion does and clarif ...

What is the method utilized by Redux to store data?

I am currently developing a small application to enhance my understanding of how to utilize redux. Based on my research, redux allows you to store and update data within the store. In my application, I have implemented an HTML form with two text inputs. Up ...