How to throw multiple alerts in validations in Javascript

Viewed 35

I am trying to validate the form, and each form value is having its own validation criteria. And I need to throw the message of each validation which is failing as alert. I am able to do so, but I am getting that in same line. But I need to put the each sentence in different line.

enter image description here

I am able to get the correct answer in my console (i.e each error in different line).

I am validating each validation criteria and pushing the errors from each validation in an array. If array is non empty i.e if we are having an error. It will return that error array else go on submit that details to 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>
1 Answers

What is happening is you're merging all errors into one errorMessage. But, you have to do is iterate and show an alert for each error. So, it'd be something like:

<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>
Related