Angular 2 Trigger Form Validation on Submit
Solution 1
If you are using Template Driven Form you can use this syntax:
<form #f="ngForm" (submit)="add(f.valid)" novalidate>
<button type="submit">Save</button>
</form>
.ts
add(isValid: boolean){
if(isValid){
//do something
}
}
you can also add some errors on submit like this:
<form #f="ngForm" (submit)="add(f.valid)" novalidate>
<label>Name</label>
<div>
<input [(ngModel)]="name" name="name" #name="ngModel" required>
</div>
<div[hidden]="name.valid || (name.pristine && !f.submitted)">
<small class="text-danger">Please input name</small>
</div>
<button type="submit">Save</button>
</form>
Solution 2
The validation should be executed everytime you change the model. But perhaps you can't see the error message because the FormControl is untouched? Here is my solution which works fine.
I did it with the following easy steps:
- Implement a FormComponent (selector "form") which injects the formGroupDirective (subscribe to the submit event and set submitted as true)
@Component({ selector: 'form', templateUrl: 'form.component.html', styleUrls: ['form.component.scss'] }) export class FormComponent implements OnInit { @Output() submit = new EventEmitter(); constructor(@Optional() private formGroupDirective: FormGroupDirective) { } ngOnInit() { if (this.formGroupDirective) { this.formGroupDirective.ngSubmit.subscribe(() => { this.formGroupDirective.form['submitted'] = true; }); } } }
The important lines are in ngOnInit
Check for form submitted to show the error
*ngIf="control?.hasError('required') && (control?.touched || form?.submitted)"
Hope that helps
Snake
Updated on July 18, 2022Comments
-
Snake almost 2 years
I created a form with angular 2 and added some custome validators. Now i want to trigger the form validation if the user clicks on the submit button. In the examples i have found so far the submit button is disabled as long as the form is invalid but i want to have the submit button always enable and when the user clicks on submit the form should be validated. Does anybody know how i can make this work and which typescript method i should use? I have found the updateValueAndValidity method but it doesn´t seem to work with this method.
-
Snake over 7 yearsThanks for your help but i am using the model driven approach because my form is created dynamically. The problem is the validation seems to work but the errors are not displayed.
-
Daniel Carabott over 7 yearsProbably you've set the validations to show whenever the form is touched/dirty etc. If you submit an empty form, the validations won't show since its still 'untouched'. I haven't found a solution yet.
-
Aldracor over 6 yearsif your submit button is outside your form use the form attribute <button type="submit" form="myform" >Submit</button> <form name="myform" #f="ngForm" (ngSubmit)="save($event)"
-
Yuriy Yakovenko over 6 yearsI knew it) it was rhetorical question
-
Senthil over 6 yearsThanks for you help.