Reactive Forms - mark fields as touched
AngularAngular Reactive-FormsAngular2 FormsAngular2 FormbuilderAngular Problem Overview
I am having trouble finding out how to mark all form's fields as touched.
The main problem is that if I do not touch fields and try to submit form - validation error in not shown up. I have placeholder for that piece of code in my controller.
My idea is simple:
- user clicks submit button
- all fields marks as touched
- error formatter reruns and displays validation errors
If anyone have other idea how to show errors on submit, without implementing new method - please share them. Thanks!
My simplified form:
<form class="form-horizontal" [formGroup]="form" (ngSubmit)="onSubmit(form.value)">
<input type="text" id="title" class="form-control" formControlName="title">
<span class="help-block" *ngIf="formErrors.title">{{ formErrors.title }}</span>
<button>Submit</button>
</form>
And my controller:
import {Component, OnInit} from '@angular/core';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';
@Component({
selector : 'pastebin-root',
templateUrl: './app.component.html',
styleUrls : ['./app.component.css']
})
export class AppComponent implements OnInit {
form: FormGroup;
formErrors = {
'title': ''
};
validationMessages = {
'title': {
'required': 'Title is required.'
}
};
constructor(private fb: FormBuilder) {
}
ngOnInit(): void {
this.buildForm();
}
onSubmit(form: any): void {
// somehow touch all elements so onValueChanged will generate correct error messages
this.onValueChanged();
if (this.form.valid) {
console.log(form);
}
}
buildForm(): void {
this.form = this.fb.group({
'title': ['', Validators.required]
});
this.form.valueChanges
.subscribe(data => this.onValueChanged(data));
}
onValueChanged(data?: any) {
if (!this.form) {
return;
}
const form = this.form;
for (const field in this.formErrors) {
if (!this.formErrors.hasOwnProperty(field)) {
continue;
}
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.touched && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
if (!control.errors.hasOwnProperty(key)) {
continue;
}
this.formErrors[field] += messages[key] + ' ';
}
}
}
}
}
Angular Solutions
Solution 1 - Angular
From Angular 8 you can simply use
this.form.markAllAsTouched();
To mark a control and it's descendant controls as touched.
Solution 2 - Angular
The following function recurses through controls in a form group and gently touches them. Because the control's field is an object, the code call Object.values()
on the form group's control field.
/**
* Marks all controls in a form group as touched
* @param formGroup - The form group to touch
*/
private markFormGroupTouched(formGroup: FormGroup) {
(<any>Object).values(formGroup.controls).forEach(control => {
control.markAsTouched();
if (control.controls) {
this.markFormGroupTouched(control);
}
});
}
Solution 3 - Angular
Regarding to @masterwork's answer. I tried that solution, but I got an error when the function tried to dig, recursively, inside a FormGroup, because there is passing a FormControl argument, instead of a FormGroup, at this line:
control.controls.forEach(c => this.markFormGroupTouched(c));
Here is my solution
markFormGroupTouched(formGroup: FormGroup) {
(<any>Object).values(formGroup.controls).forEach(control => {
if (control.controls) { // control is a FormGroup
markFormGroupTouched(control);
} else { // control is a FormControl
control.markAsTouched();
}
});
}
Solution 4 - Angular
From Angular v8, you have this built-in with the help of the markAllAsTouched
method.
As an example, you could use it like
form.markAllAsTouched();
See the official doc : https://angular.io/api/forms/AbstractControl#markallastouched
Solution 5 - Angular
Looping through the form controls and marking them as touched would also work:
for(let i in this.form.controls)
this.form.controls[i].markAsTouched();
Solution 6 - Angular
This is my solution
static markFormGroupTouched (FormControls: { [key: string]: AbstractControl } | AbstractControl[]): void {
const markFormGroupTouchedRecursive = (controls: { [key: string]: AbstractControl } | AbstractControl[]): void => {
_.forOwn(controls, (c, controlKey) => {
if (c instanceof FormGroup || c instanceof FormArray) {
markFormGroupTouchedRecursive(c.controls);
} else {
c.markAsTouched();
}
});
};
markFormGroupTouchedRecursive(FormControls);
}
Solution 7 - Angular
I had this issue but found the "correct" way of doing so, despite it not being in any Angular tutorial I've ever found.
In your HTML, on the form
tag, add the same Template Reference Variable #myVariable='ngForm'
('hashtag' variable) that the Template-Driven Forms examples use, in addition to what the Reactive Forms examples use:
<form [formGroup]="myFormGroup" #myForm="ngForm" (ngSubmit)="submit()">
Now you have access to myForm.submitted
in the template which you can use instead of (or in addition to) myFormGroup.controls.X.touched
:
<span *ngIf="myFormGroup.controls.myFieldX.errors?.badDate">invalid date format</span>
<span *ngIf="myFormGroup.controls.myFieldX.errors?.isPastDate">date cannot be in the past.</span>
</div>
Know that myForm.form === myFormGroup
is true... as long as you don't forget the ="ngForm"
part. If you use #myForm
alone, it won't work because the var will be set to the HtmlElement instead of the Directive driving that element.
Know that myFormGroup
is visible in your Component's typescript code per the Reactive Forms tutorials, but myForm
isn't, unless you pass it in through a method call, like submit(myForm)
to submit(myForm: NgForm): void {...}
. (Notice NgForm
is in title caps in the typescript but camel case in HTML.)
Solution 8 - Angular
onSubmit(form: any): void {
if (!this.form) {
this.form.markAsTouched();
// this.form.markAsDirty(); <-- this can be useful
}
}
Solution 9 - Angular
I ran into the same problem, but I do not want to "pollute" my components with code that handles this. Especially since I need this in many forms and I do not want to repeat the code on various occasions.
Thus I created a directive (using the answers posted so far). The directive decorates NgForm's onSubmit
-Method: If the form is invalid it marks all fields as touched and aborts submission. Otherwise the usual onSubmit-Method executes normally.
import {Directive, Host} from '@angular/core';
import {NgForm} from '@angular/forms';
@Directive({
selector: '[appValidateOnSubmit]'
})
export class ValidateOnSubmitDirective {
constructor(@Host() form: NgForm) {
const oldSubmit = form.onSubmit;
form.onSubmit = function (): boolean {
if (form.invalid) {
const controls = form.controls;
Object.keys(controls).forEach(controlName => controls[controlName].markAsTouched());
return false;
}
return oldSubmit.apply(form, arguments);
};
}
}
Usage:
<form (ngSubmit)="submit()" appValidateOnSubmit>
<!-- ... form controls ... -->
</form>
Solution 10 - Angular
This is the code that I am actually using.
validateAllFormFields(formGroup: any) {
// This code also works in IE 11
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.markAsTouched({ onlySelf: true });
} else if (control instanceof FormGroup) {
this.validateAllFormFields(control);
} else if (control instanceof FormArray) {
this.validateAllFormFields(control);
}
});
}
Solution 11 - Angular
This code works for me:
markAsRequired(formGroup: FormGroup) {
if (Reflect.getOwnPropertyDescriptor(formGroup, 'controls')) {
(<any>Object).values(formGroup.controls).forEach(control => {
if (control instanceof FormGroup) {
// FormGroup
markAsRequired(control);
}
// FormControl
control.markAsTouched();
});
}
}
Solution 12 - Angular
A solution without recursion
For those worried about performance, I've come up with a solution that doesn't use recursion, although it still iterates over all controls in all levels.
/**
* Iterates over a FormGroup or FormArray and mark all controls as
* touched, including its children.
*
* @param {(FormGroup | FormArray)} rootControl - Root form
* group or form array
* @param {boolean} [visitChildren=true] - Specify whether it should
* iterate over nested controls
*/
public markControlsAsTouched(rootControl: FormGroup | FormArray,
visitChildren: boolean = true) {
let stack: (FormGroup | FormArray)[] = [];
// Stack the root FormGroup or FormArray
if (rootControl &&
(rootControl instanceof FormGroup || rootControl instanceof FormArray)) {
stack.push(rootControl);
}
while (stack.length > 0) {
let currentControl = stack.pop();
(<any>Object).values(currentControl.controls).forEach((control) => {
// If there are nested forms or formArrays, stack them to visit later
if (visitChildren &&
(control instanceof FormGroup || control instanceof FormArray)
) {
stack.push(control);
} else {
control.markAsTouched();
}
});
}
}
This solution works form both FormGroup and also FormArray.
You can play around with it here: angular-mark-as-touched
Solution 13 - Angular
as per @masterwork
typescript code for the angular version 8
private markFormGroupTouched(formGroup: FormGroup) {
(Object as any).values(formGroup.controls).forEach(control => {
control.markAsTouched();
if (control.controls) {
this.markFormGroupTouched(control);
}
}); }
Solution 14 - Angular
Here is how I do it. I don't want the error fields to show until after the submit button is pressed (or the form is touched).
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {OnInit} from "@angular/core";
export class MyFormComponent implements OnInit {
doValidation = false;
form: FormGroup;
constructor(fb: FormBuilder) {
this.form = fb.group({
title: ["", Validators.required]
});
}
ngOnInit() {
}
clickSubmitForm() {
this.doValidation = true;
if (this.form.valid) {
console.log(this.form.value);
};
}
}
<form class="form-horizontal" [formGroup]="form" >
<input type="text" class="form-control" formControlName="title">
<div *ngIf="form.get('title').hasError('required') && doValidation" class="alert alert-danger">
title is required
</div>
<button (click)="clickSubmitForm()">Submit</button>
</form>
Solution 15 - Angular
I completely understand the OP's frustration. I use the following:
Utility function:
/**
* Determines if the given form is valid by touching its controls
* and updating their validity.
* @param formGroup the container of the controls to be checked
* @returns {boolean} whether or not the form was invalid.
*/
export function formValid(formGroup: FormGroup): boolean {
return !Object.keys(formGroup.controls)
.map(controlName => formGroup.controls[controlName])
.filter(control => {
control.markAsTouched();
control.updateValueAndValidity();
return !control.valid;
}).length;
}
Usage:
onSubmit() {
if (!formValid(this.formGroup)) {
return;
}
// ... TODO: logic if form is valid.
}
Note that this function does not yet cater for nested controls.
Solution 16 - Angular
See this gem. So far the most elegant solution I've seen.
Full code
import { Injectable } from '@angular/core';
import { FormGroup } from '@angular/forms';
const TOUCHED = 'markAsTouched';
const UNTOUCHED = 'markAsUntouched';
const DIRTY = 'markAsDirty';
const PENDING = 'markAsPending';
const PRISTINE = 'markAsPristine';
const FORM_CONTROL_STATES: Array<string> = [TOUCHED, UNTOUCHED, DIRTY, PENDING, PRISTINE];
@Injectable({
providedIn: 'root'
})
export class FormStateService {
markAs (form: FormGroup, state: string): FormGroup {
if (FORM_CONTROL_STATES.indexOf(state) === -1) {
return form;
}
const controls: Array<string> = Object.keys(form.controls);
for (const control of controls) {
form.controls[control][state]();
}
return form;
}
markAsTouched (form: FormGroup): FormGroup {
return this.markAs(form, TOUCHED);
}
markAsUntouched (form: FormGroup): FormGroup {
return this.markAs(form, UNTOUCHED);
}
markAsDirty (form: FormGroup): FormGroup {
return this.markAs(form, DIRTY);
}
markAsPending (form: FormGroup): FormGroup {
return this.markAs(form, PENDING);
}
markAsPristine (form: FormGroup): FormGroup {
return this.markAs(form, PRISTINE);
}
}
Solution 17 - Angular
/**
* Marks as a touched
* @param { FormGroup } formGroup
*
* @return {void}
*/
markFormGroupTouched(formGroup: FormGroup) {
Object.values(formGroup.controls).forEach((control: any) => {
if (control instanceof FormControl) {
control.markAsTouched();
control.updateValueAndValidity();
} else if (control instanceof FormGroup) {
this.markFormGroupTouched(control);
}
});
}
Solution 18 - Angular
View:
<button (click)="Submit(yourFormGroup)">Submit</button>
API
Submit(form: any) {
if (form.status === 'INVALID') {
for (let inner in details.controls) {
details.get(inner).markAsTouched();
}
return false;
}
// as it return false it breaks js execution and return
Solution 19 - Angular
I made a version with some changes in the answers presented, for those who are using versions older than version 8 of the angular, I would like to share it with those who are useful.
Utility function:
import {FormControl, FormGroup} from "@angular/forms";
function getAllControls(formGroup: FormGroup): FormControl[] {
const controls: FormControl[] = [];
(<any>Object).values(formGroup.controls).forEach(control => {
if (control.controls) { // control is a FormGroup
const allControls = getAllControls(control);
controls.push(...allControls);
} else { // control is a FormControl
controls.push(control);
}
});
return controls;
}
export function isValidForm(formGroup: FormGroup): boolean {
return getAllControls(formGroup)
.filter(control => {
control.markAsTouched();
return !control.valid;
}).length === 0;
}
Usage:
onSubmit() {
if (this.isValidForm()) {
// ... TODO: logic if form is valid
}
}