0

In my application, I am trying angular validator. If the form is already filled with data, then the validation is perfect. But if no data is filled initially and if I click on the button, then it is not showing the errors. But if I click on some fields and blur, then it will show the error for that field.

How can I make the error show when click on the button?

validation.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ValidationService {

  constructor() { }

  static getValidatorErrorMessage(validatorName: string, validatorValue?: any) {
    const config = {
      required: 'validation.required',
      minlength: `Minimum length is ${validatorValue.requiredLength}`,
      email: 'validation.email',
    };
    return config[validatorName];
  }
}

validation-message.component.ts

import { Component, Input } from '@angular/core';
import { FormControl } from '@angular/forms';
import { ValidationService } from '../../services/validation/validation.service';
@Component({
  selector: 'app-errorMessages',
  template: `<div *ngIf="errorMessage !== null">{{errorMessage | translate}}</div>`
})
export class ValidationMessagesComponent {

  @Input() control: FormControl;

  constructor() { }

  /**
   * Function to get the form validation error message
   *
   * @readonly
   * @memberof ValidationMessagesComponent
   */
  get errorMessage() {
    for (const propertyName in this.control.errors) {
      if (this.control.errors.hasOwnProperty(propertyName) && this.control.touched) {
        return ValidationService.getValidatorErrorMessage(propertyName, this.control.errors[propertyName]);
      }
    }
    return null;
  }
}

HTML portion to show the error

<app-errorMessages [control]="userForm.controls.userFullName" class="error-msg messages text-left text-danger"></app-errorMessages>

Button to initiate submit

<button type="button" class="btn btn-primary btn-lg btn-block"  ngIf="submitFlag" (click)="onSubmit()">Save</button>

Functions associated with submit

onSubmit(): any {
    // Component points data to the module and module points to the http service
    // use the retun value to trigger a toast Message.
    console.log(this.userForm);
    if (!this.validateUserForm()) {
      console.log('Show errors');
      return false;
    }
    this.userService.createNewUser(this.userForm.value);
  }

validateUserForm() {
    if (this.userForm.invalid) {
      return false;
    }
    return true;
  }
4

1 回答 1

1

你希望你的条件看起来更像这样:

 if (this.control.errors.hasOwnProperty(propertyName) && (this.control.touched || this.control.submitted)) 

然后您还需要在表单元素中使用 ngSubmit 指令并更改您的按钮类型以提交以使其工作

于 2019-08-05T13:14:36.297 回答