Home > other >  Reactive Form Validation on Button Click
Reactive Form Validation on Button Click

Time:09-17

I am trying to validate input field in Angular project and using a tutorial, seems it's working as expected.

Validation in Angular

The above uses Reactive Form that does the work for validation as follows:

<form [formGroup]="angForm" novalidate>
    <div class="form-group">
        <label>Name:</label>
        <input class="form-control" formControlName="name" type="text">
    </div>
    <div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['name'].errors.required">
          Name is required.
        </div>
    </div>
     <div class="form-group">
        <label>Address:</label>
        <input class="form-control" formControlName="address" type="text">
    </div>
    <div *ngIf="angForm.controls['address'].invalid && (angForm.controls['address'].dirty || angForm.controls['address'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['address'].errors.required">
          email is required.
        </div>
    </div>
    <button type="submit"
        [disabled]="angForm.pristine || angForm.invalid" class="btn btn-success">
        Save
    </button>
</form>

The button is disabled by default in the above. So when user start writing and keeps an input field blank, then it validates the form. My requirement is to enable the button and when clicked, the validation will be working. So what I did is as follows:

<form [formGroup]="angForm" #addData='ngForm' (ngSubmit)="AddData(addData)">

<button type="submit" class="btn btn-success"> //Removed the disabled property
   Save
</button> 

In TypeScript did this:

AddData(addData: NgForm) {
  this.createForm();
}

createForm() {
  this.angForm = this.fb.group({
    name: ['', Validators.required ]
  });
}

Though it doesn't trigger the validation as expected. So what I want is to trigger validation on button click that I am unable to do here. Any way that can be resolved?

CodePudding user response:

Maybe you can add a little logic on your AddData function:

AddData() {
  if (this.angForm.valid) {
    //Logic for valid form
  } else {
    Object.keys(this.angForm.controls).forEach(field => {
    const control = this.form.get(field);
    control.markAsTouched({ onlySelf: true });
   });
  }
}

This will mark the elements as touched when the person clicks the button, which will trigger the logic used to show error messages and styles on inputs, assuming is:

!this.angForm.controls['name'].valid && this.angForm.controls['name'].touched;
  • Related