Do not fire Form Validation in angular 2 on blur

I was able to integrate form validation in angular 2.

I am using form = formBuilder.group({...}) method.

Validations work good. But I want validation to be fired only when I click submit. Currently by default it fires up when user blur from an input. How to stop firing validation on blur and fire it manual.

EDIT:

Problem with using *ngIf or [hidden] is that they work fine with variables to keep track of form submission. But validation only fires when i blur from the input. In other way validation does not fire when user has not visited the input.

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

You need to integrate a custom formSubmitted property into your expression to display errors. For example:

<span *ngIf="formSubmitted && form.controls.someCtrl.errors?.someerror">
  Some message
</span>

By default its value is false and will be set to true when the form is submitted.

@Component({
  (...)
  template: `
    <form (ngSubmit)="onFormSubmitted()">
    </form>
  `
})
export class SomeComponent {
  formSubmitted: boolean = false;

  onFormSubmitted() {
    this.formSubmitted = true;
  }
}

Jason
Guest

Show the errors only when the submitted flat is set:

 <form (ngSubmit)="submit()" ...>
 <input ngControl="name" #name="ngForm" type="text">
 <span [hidden]="name.valid && isSubmitted"><b>Required</b></span>
 </form>
class MyComponent {
  isSubmitted:boolean = false;

  submit() {
    this.isSubmitted = true;
  }
}