Reactive Forms - mark fields as touched

2019-01-22 18:54发布

问题:

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:

  1. user clicks submit button
  2. all fields marks as touched
  3. 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] + ' ';
        }
      }
    }
  }
}

回答1:

The following function recurses through controls in a form group and gently touches them. Because the controls 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);
      }
    });
  }


回答2:

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();


回答3:

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);
      }


回答4:

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();
   }
 });
}


回答5:

onSubmit(form: any): void {
  if (!this.form) {
    this.form.markAsTouched();
    // this.form.markAsDirty(); <-- this can be useful 
  }
}


回答6:

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>



回答7:

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:

<div *ngIf="myForm.submitted" class="text-error"> <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.)



回答8:

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>


回答9:

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);
        }
    });
}    



回答10:

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();
    });
  }
}


回答11:

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.