简体   繁体   中英

Show errors messages only after form submit

I am creating Angular 6 Form with validation. I want to show error messages only after submitting the form. Important fact is that messages SHOULD NOT change during the typing. So for example when the user hasn't typed anything in input and then submitted the form, the required messages should appear. After that when user types something, the messages should be visible all the time until the next submitt button press. Also the error messages shouldn't change to another when previous rule was fulfiled. To be honest I don't know if it is possible using Reactive Forms.

app.component.html

<form [formGroup]="form" novalidate (ngSubmit)="submit()" #myform="ngForm">
    <input class="input" type="text" formControlName="firstName" />   
    <p *ngIf="form.get('firstName').hasError('required') && myform.submitted">
      Name is required
    </p>
    <p *ngIf="form.get('firstName').hasError('minlength') && myform.submitted">
      Min length of string is {{form.controls.firstName.errors.minlength.requiredLength}}    
    </p>
    <button type="submit">Submit</button>
</form> 

app.component.ts

export class AppComponent  {
  form: FormGroup
  constructor(private fb: FormBuilder,) {
      this.form = this.fb.group({
          firstName: ['', [Validators.required, Validators.minLength(5)]]
      });
  }

  submit() {
    console.log(this.form);
  }
}

DEMO: stackblitz

Thanks for any help!

You could check the validation in the submit function like this:

<p *ngIf="requiredError">
  Name is required
</p>
<p *ngIf="invalid">
  Min length of string is {{form.controls.firstName.errors.minlength.requiredLength}}    
</p>

  invalid: boolean;
  requiredError: boolean;
  submit() {
    console.log(this.form);
    this.invalid = this.form.get('firstName').hasError('minlength');
    this.requiredError = this.form.get('firstName').hasError('required');
  }

From Angular 7 you can use: {updateOn:'submit'} or {updateOn:'blur'}

*Update using new FormGroup and new FormControl (using formBuilder not work)

Use {updateOn:'blur'} when you want to correct the error is lost focus the input, {updateOn:'submit'} if it's only when submit

this.form = new FormGroup({
        firstName:new FormControl('', 
          [Validators.required, Validators.minLength(5)])
      },{updateOn:'submit'});

*Update 2 if you want use with formBuilder see the answer to Q in stackoverflow

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM