Getting error in validation while submitting the form in angular

ria

I have a form, inside the form i have following fields: name (textbox), id(textbox) type(textbox), category(dropdown) I'm showing a textbox on selecting the dropdown option with value "3". And when i click on add new text field after selection of dropdown with value "3", I'm calling a form array, where i get multiple textboxes.

I updated my code for reference in Stackblitz :

https://stackblitz.com/edit/angular-ivy-vlvbqz?file=src%2Fapp%2Fapp.component.ts

<form [formGroup]="addForm" (ngSubmit)="onSubmit()">
                   
                          <input type="text" class="form-control" placeholder="enter term"
                          formControlName="name">   
                          <small class="errormessage" *ngIf="submitted && addForm.controls.name.hasError('required')">
                            Term is required
                          </small>
                
                        <input type="text" class="form-control" placeholder="Enter Id"
                        formControlName="id">   
            
<small class="errormessage" *ngIf="submitted && addForm.controls.id.hasError('required')">
                            id is required 
                        </small>
                        
                        <input type="text" class="form-control" placeholder="Type" formControlName="type">
<small class="errormessage" *ngIf="submitted && addForm.controls.type.hasError('required')">
                            type is required 
                        </small>
                                      

                        <select class="Dropdown" formControlName="category" [(ngModel)]="optionValue">
                            <option value="undefined" selected disabled >Select Category</option>
                            <option  *ngFor="let list of dropdownitems" [value]="list.id" >{{list.name}}</option>
                        </select> 

                        <small class="errormessage" *ngIf="submitted && addForm.controls.category.hasError('required')">
                            Category is required 
                        </small>


                    <ng-container *ngIf="optionValue == '3'">
                                               
                          <input type="text" formControlName="listItem" class="form-control" placeholder="enter dropdownlist items"> 
                        <small class="errormessage" *ngIf="submitted && addForm.controls.listItem.hasError('required')">
                            Category is required 
                        </small>
                          <a (click)="addGroup()">Add New Textfield</a>

                    </ng-container>
                    
                     <span formArrayName="times" *ngFor="let time of addForm.controls.times?.value; let i = index;">                          
                      <span [formGroupName]="i">                         
                            <input type="text" class="form-control" formControlName="lists" placeholder="enter dropdown options">  

                      </span>
                     <a(click)="removeGroup(i)">Remove Textfield</a>
                     </span>                   
                     
                          <input type="Submit" class="savebtn" Value="Save" Style="width: 100px;"/>&nbsp;
 
                  </form>

In ts i'm validating all the fields. onSubmit() function, if the form is invalid i'm showing an alert. Right now, when i submit the form without selecting the dropdown option as "3". (means my form doesn't show list item textfield). and even if i give name, id, type and select dropdown value as 1, even without selecting 3. It, should not show form invalid. But,i'm getting form invalid eventhough there is no new textbox in my form (as i didn't select 3).

Please correct my code and help me achieve this functionality.

 ngOnInit(): void {
    this.addForm = this.formBuilder.group({
      name: ['', [Validators.required, Validators.pattern('[a-zA-Z# ]*')]],
      id:  ['', [Validators.required]],
      type:  ['', [Validators.required]],
      category: ['', [Validators.required]],
      listItem: ['', [Validators.required]],
      times: this.formBuilder.array([])
      }); 
    console.log(this.addForm.value);
  }

public dropdownitems = [{
    name: "A",
    id: 1
  },{
    name: "B",
    id: 2
  },{
    name: "B",
    id: 3   
  },{
    name: "D",
    id: 4    
  }]

  onSubmit(){
    this.submitted = true;
    if (this.addForm.invalid) {
      alert ('Please fill up complete details');
      return;
    }
    console.log(this.addForm.value);   
}


value = this.formBuilder.group({
  lists: ['', Validators.required],
});


addGroup() {
  const val = this.formBuilder.group({
    lists: ['', Validators.required],
  });
  const form = this.addForm.get('times') as FormArray;
  form.push(val);
}

removeGroup(index) {
  const form = this.addForm.get('times') as FormArray;
  form.removeAt(index);
}

}

Hugo Noro

The problem is that even if the fields are hidden in the template (HTML) they are defined in the form as required.

You need to either add and remove the form fields conditionally or you need to make them enabled / disabled to ignore the required flag.

Sharing here the fixed Stackblitz with a possible solution and small improvement (removed the ngModel

You have a similar issue raised on this thread form validation on hidden fields

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Angular form submitting despite validation error

getting form data in node js:undefined error while submitting form

How to check validation while submitting form using angular.js

Getting error in Angular Reactive form validation

Form Validation error on correctly submitting the form

Email Value Validation Error when submitting form

How to stop triggering other function if validation function throws error while submitting html form using jQuery and html?

Angular reactive form is getting sumitted without submitting

Getting undefined error when submitting form

Spring Boot error while submitting form

Error while submitting the form data in vuejs

getting an error not related to form validation

jQuery Validation and submitting a form

I am getting an error in django project while submitting the form can any one please tell the correction of my error

The page is getting reset on submitting form after a while in HTML, javascript

Input field validation before submitting form in Angular 4

Form not submitting after form validation

html5 validation error message without submitting form

how to clear validation errors for mat error after submitting the form

Angular: form validation causing an error

Reactive Form Validation Error in Angular

Getting error "InvalidAddress" while submitting Amazon MWS CreateInboundShipmentPlan

Getting error Cannot POST /public/register-controller on submitting the form

laravel updating editing database record - getting error when submitting the form

Django - Getting 405 error when submitting contact form

Getting an "undefined method `permit' for "create"" error when submitting form

Angular form validation not getting fired for author field

I have an AMP form but for some reason it has error while submitting

Ember DS.Store error while submitting form

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive