angularangular-formsangular2-form-validation

How to trigger form validations (only) when submitting the form?


I created a dynamic form, in which you can add or remove fields with dedicated buttons:

![enter image description here

The problem is that when we add a new field, the form validations are immediately triggered causing the error messages to be displayed:

enter image description here

I would like to trigger it only if the user try to submit the form when there are errors. And of course the form cannot be submitted if there are errors (Validators.required, nicknameValidator())

Here is the code that generate a new row in the form:

createNicknameFormGroup(): any {
  return new FormGroup({
    nickname: new FormControl('', Validators.required, this.isValidNicknameService.nicknameValidator())
  }, { updateOn: 'blur' })
}

And the html code responsible of displaying those rows:

<div *ngFor="let nickname of nicknamesFormArray.controls; let i = index;" class="row">

  <div [formGroupName]="i">

    <mat-form-field appearance="outline" class="nickname-form-field">
      <mat-label>{{formFieldsInfo.nicknames.label}}</mat-label>
      <input matInput [placeholder]=formFieldsInfo.nicknames.placeholder formControlName="nickname"
             type="text"
             class="form-control">
      <mat-hint>{{formFieldsInfo.nicknames.hint}}</mat-hint>
      <mat-error *ngIf="nicknamesFormArray.controls[i].get('nickname').errors?.required">
        {{formFieldsInfo.nicknames.errorMessages.required}}
      </mat-error>
      <mat-error *ngIf="nicknamesFormArray.controls[i].get('nickname').errors?.shouldNotStartWithA">
        {{formFieldsInfo.nicknames.errorMessages.shouldNotStartWithA}}
      </mat-error>
    </mat-form-field>

    <mat-icon (click)="removeNicknameFromNicknamesFormArray(i)" class="clear">
      clear
    </mat-icon>

  </div>

</div>

Solution

    1. Not set validator. Just let empty.
    2. When submit (what just button) and you can add validator runtime by setValidators() and setErrors() if you want.
    3. After there are/is error(s), you have to clean validators with empty array into setValidators()

    https://angular.io/api/forms/AbstractControl#setValidators https://angular.io/api/forms/AbstractControl#setErrors

    I recommend read more API options.