angular2 validate form on button click

2019-04-05 09:03发布

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>  

7条回答
我想做一个坏孩纸
2楼-- · 2019-04-05 09:45

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]
查看更多
Explosion°爆炸
3楼-- · 2019-04-05 09:47

Put your click2 button within form tag. It will start working !

<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>     
  <!-- this will work now -->
  <button (click)="save()">Click 2</button>      
</form>
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-04-05 09:49

put conditions in [hidden] directive and change submitted property to true on submit!

<div [hidden]="email.valid || (email.untouched && !submitted) || !submitted" class="alert callout">
    <span [hidden]="!email.hasError('required')">Required</span>
</div>

onSubmit(){
   this.submitted = true
}
查看更多
欢心
5楼-- · 2019-04-05 09:55

You should keep the button disabled until the form is valid. So in your case change your form element opening tag to create a variable for the form:

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

and disable the button when the form isn't valid

<button (click)="save()" [disabled]="!myForm.form.valid">Click 2</button>

Let me know if that works. As the form itself will validate automatically and constantly in anycase, you dont need to call for it to be done.

查看更多
Fickle 薄情
6楼-- · 2019-04-05 10:05

Below Code Will Help You .. Tested with Angular 4 Latest version 4.2.4

<form method="post" #f="ngForm" name="form" novalidate="novalidate" class="form">
   <div class="row">
      <div class="form-group col-sm-12" [ngClass]="{'has-error':!listname.valid && (listname.dirty || listname.touched || f.submitted)}">
         <label for="listname">Name</label>
         <input id="listname" name="listname" type="text" [(ngModel)]="listData.title"
         required="true" placeholder="List Name" #listname="ngModel" class="form-control"/>
      </div>
   </div>
   <div class="row">
      <div class="form-group text-right col-md-12 visible-md visible-lg">
         <button type="button"  name="save"  (click)="f._submitted = true;saveAndPublish=false;saveList(f.valid)" class="btn btn-default">Save
         Save List
         </button>
         <button type="button"  name="saveandpublish" (click)="f._submitted = true;saveAndPublish=true;saveList(f.valid);" class="btn btn-primary">Save
         & Publish  List
         </button>
      </div>
   </div>
</form>

in Your .ts File

saveList(isValid: boolean) {
    if (isValid) {
      console.log(this.listData)
    }

  }
查看更多
家丑人穷心不美
7楼-- · 2019-04-05 10:08

Programatically check and disable using validation

<form class="form-horizontal" id='myForm' role="form" [ngFormModel]="CreateGroup">
  <div class="col-md-7">
    Name: <input type="text" [(ngModel)]='demoInfo.name' class="form-control" ngControl='name'>
  </div>
  Form Valid : {{CreateGroup.valid}} 
</form>
<br>
<div class='text-center'>
  <button type="button" [disabled]='!CreateGroup.valid' (click)="addNewGroup(demoInfo)" class="btn btn-primary">Create</button>
</div>

working example http://plnkr.co/edit/aoHHw709VeMlP8Qfgnp6?p=preview

查看更多
登录 后发表回答