简体   繁体   中英

Show errors in Angular2 forms if form items empty, but user submit form

I have a userForm group which has keys name , email and phone . Also I have a onValueChanged function which one subscribes to form changes and validate data.

 buildForm(): void {
    this.userForm = this.fb.group({
      'name': ['', [
          Validators.required,
        ]
      ],
      'email': [''],
      'phone':    ['', Validators.required]
    });

this.userForm.valueChanges
  .subscribe(data => this.onValueChanged(data));

Also I have a submit button, but if user doesn't print any data and submit form my errors doesn't show. How can I fix it?

onSubmit() {
    this.submitted = true;
}

This is my errors:

formErrors = {
    'name': '',
    // ...
  };

  validationMessages = {
    'name': {
      'required':      'Name is required.',
      'minlength':     'Name must be at least 4 characters long.',
      // ...
    },
    // ...
  };
}

My onValueChanged function:

 onValueChanged(data?: any): void {
    if (!this.registrationForm) return;
    const form = this.registrationForm;

    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control: any = form.controls[field];

      if (control && control.dirty && !control.valid) {
        const messages: string = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

I use my validation in template like this:

<div [ngClass]="formErrors.email ? 'has-danger' : '' ">
    <label for="email">Email <span class="text-danger">*</span></label>
    <input type="email" formControlName="email"  id="email">
    <div class="form-control-feedback">{{formErrors.email}}</div>
</div>

You need to write ngif statements in your component.html(html or your html file). Such as below for phone formControl:

  <div *ngIf="!phone.valid && (phone.touched || submitted)">Required</div>

Added phone.touched , so that error displays only after formControl has been touched by user.

Added submitted , so that error displays only after user has attempted to submit form.

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