Reputation: 803
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!
Upvotes: 5
Views: 8392
Reputation: 57939
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
Upvotes: 7
Reputation: 2594
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');
}
Upvotes: 2