Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 validate form on button click

If I submit a form using button type="submit" the form validation messages appear and everything is fine. However if I have a button (or link) with (click)="myhandler()" then the validations do not appear.

How can I either:

  • tag the element as requiring validators to run, or
  • programatically run and show validation messages.

Note: These are simple validations like required on input fields.

Sample Code:

<form (ngSubmit)="save()">                       
  <input required type='text' [(ngModel)]="name">
  <!-- Shows validation messages but still calls save() -->
  <button (click)="save()">Click</button>  
  <!-- Only submits if valid and shows messages -->       
  <button type="submit">Submit</button>         
</form>
<!-- does not even show validation messages, just calls save -->
<button (click)="save()">Click 2</button>  
like image 827
gatapia Avatar asked Apr 12 '16 09:04

gatapia


2 Answers

Please note: this approach is for reactive forms.

I used markAsTouched() property to run validations on a button click.

Suppose the following button is outside the form:

<button type="button" (click)="validateForm()">Submit</button>

Now, in the validateForm method if the form is invalid, you can set markAsTouched() property for each of the form controls and angular will show validation messages.

validateForm() {
    if (this.myformGroup.invalid) {
      this.myformGroup.get('firstName').markAsTouched();
      this.myformGroup.get('surname').markAsTouched();
      return;
    }
    // do something else
}

provided you have validation messages setup in your html like

<mat-error *ngIf="myformGroup.get('firstName').hasError('required')">
  first name is required
</mat-error>

and you have required field validation setup in your form group builder like

firstName: ['', Validators.required]
like image 70
Sandeep Avatar answered Sep 21 '22 06:09

Sandeep


Button with type submit triggers form submit automatically, i guess you have to trigger form submit manually:

<form (ngSubmit)="save()" #form="ngForm">

<button (click)="form.onSubmit()">Click 2</button> 

Why "ngForm"? A directive's exportAs property tells Angular how to link local variable to the directive. We set name to ngForm because the NgControlName directive's exportAs property happens to be "ngForm".

documentation

like image 33
kemsky Avatar answered Sep 21 '22 06:09

kemsky